Python Lists
Python Lists
Section titled “Python Lists”Sequences are fundamental ordered collections in Python. Each item in a sequence has an assigned index, starting from 0.
Python’s built-in sequence types include strings, tuples, and lists. This chapter focuses on lists, which are one of the most versatile and commonly used data structures.
What are Lists?
Section titled “What are Lists?”A list is an ordered, mutable (changeable) sequence of items. Lists are defined by enclosing comma-separated items within square brackets []. Items in a list can be of different data types.
Creating Lists:
Section titled “Creating Lists:”# Empty listempty_list = []
# List of integersnumbers = [1, 2, 3, 4, 5]
# List of stringsnames = ["Alice", "Bob", "Charlie"]
# List with mixed data typesmixed_list = ['physics', 'chemistry', 1997, 2000]
# Nested list (list containing other lists)nested_list = [1, 2, ['a', 'b'], 3]
print(empty_list)print(numbers)print(names)print(mixed_list)print(nested_list)You can also create lists using the list() constructor, often used to convert other iterables (like tuples or strings) into lists.
tuple_example = (1, 2, 3)list_from_tuple = list(tuple_example)print(list_from_tuple) # Output: [1, 2, 3]
string_example = "hello"list_from_string = list(string_example)print(list_from_string) # Output: ['h', 'e', 'l', 'l', 'o']Accessing Values in Lists
Section titled “Accessing Values in Lists”Access items using their index inside square brackets []. Indexing starts at 0. Negative indices count from the end (-1 is the last item). Slicing [start:stop:step] works just like with strings.
#!/usr/bin/env python3
my_list = ['physics', 'chemistry', 1997, 2000, 'math']numbers = [10, 20, 30, 40, 50, 60, 70]
# Indexingprint(f"my_list[0]: {my_list[0]}") # Output: physicsprint(f"my_list[-1]: {my_list[-1]}") # Output: math
# Slicing [start:stop]print(f"numbers[1:5]: {numbers[1:5]}") # Output: [20, 30, 40, 50]print(f"numbers[:3]: {numbers[:3]}") # Output: [10, 20, 30]print(f"numbers[4:]: {numbers[4:]}") # Output: [50, 60, 70]
# Slicing with stepprint(f"numbers[::2]: {numbers[::2]}") # Output: [10, 30, 50, 70]Updating Lists (Mutability)
Section titled “Updating Lists (Mutability)”Because lists are mutable, you can change their content. You can update single items or slices by assigning new values.
#!/usr/bin/env python3
my_list = ['physics', 'chemistry', 1997, 2000]print(f"Original list: {my_list}")
# Update single elementprint(f"Value at index 2: {my_list[2]}")my_list[2] = 2001print(f"New value at index 2: {my_list[2]}")print(f"List after update: {my_list}")
# Update a slicemy_list[1:3] = ['biology', 2023] # Replace elements at index 1 and 2print(f"List after slice update: {my_list}")
# Insert elements using slicing (without removing)my_list[1:1] = ['math', 'stats'] # Insert at index 1print(f"List after slice insertion: {my_list}")Output:
Original list: ['physics', 'chemistry', 1997, 2000]Value at index 2: 1997New value at index 2: 2001List after update: ['physics', 'chemistry', 2001, 2000]List after slice update: ['physics', 'biology', 2023, 2000]List after slice insertion: ['physics', 'math', 'stats', 'biology', 2023, 2000]Adding Elements to Lists
Section titled “Adding Elements to Lists”append(item): Adds a singleitemto the end of the list.extend(iterable): Adds all items from aniterable(like another list, tuple, or string) to the end of the list.insert(index, item): Inserts anitemat the specifiedindex.
Example:
numbers = [1, 2, 3]print(f"Initial list: {numbers}")
numbers.append(4)print(f"After append(4): {numbers}")
numbers.extend([5, 6])print(f"After extend([5, 6]): {numbers}")
numbers.insert(0, 0) # Insert 0 at the beginning (index 0)print(f"After insert(0, 0): {numbers}")Output:
Initial list: [1, 2, 3]After append(4): [1, 2, 3, 4]After extend([5, 6]): [1, 2, 3, 4, 5, 6]After insert(0, 0): [0, 1, 2, 3, 4, 5, 6]Deleting List Elements
Section titled “Deleting List Elements”Several ways to remove items:
del list_name[index]: Removes the item at the specifiedindex.del list_name[start:stop]: Removes the slice.pop([index]): Removes and returns the item atindex(default is the last item, -1).remove(value): Removes the first occurrence of the specifiedvalue. RaisesValueErrorif the value is not found.
Example:
#!/usr/bin/env python3
my_list = ['physics', 'chemistry', 1997, 2000, 'math', 1997]print(f"Original list: {my_list}")
# Using del by indexdel my_list[2] # Remove item at index 2 (1997)print(f"After del my_list[2]: {my_list}")
# Using pop (removes and returns last item by default)last_item = my_list.pop()print(f"Popped item: {last_item}")print(f"List after pop(): {my_list}")
# Using pop with indexitem_at_1 = my_list.pop(1) # Remove item at index 1 ('chemistry')print(f"Popped item at index 1: {item_at_1}")print(f"List after pop(1): {my_list}")
# Using remove by valuemy_list.remove(2000)print(f"List after remove(2000): {my_list}")
# Remove first occurrence of 1997 (if still present)if 1997 in my_list: my_list.remove(1997) print(f"List after remove(1997): {my_list}")else: print("1997 not found for removal.")Output:
Original list: ['physics', 'chemistry', 1997, 2000, 'math', 1997]After del my_list[2]: ['physics', 'chemistry', 2000, 'math', 1997]Popped item: 1997List after pop(): ['physics', 'chemistry', 2000, 'math']Popped item at index 1: chemistryList after pop(1): ['physics', 2000, 'math']List after remove(2000): ['physics', 'math']1997 not found for removal.Basic List Operations
Section titled “Basic List Operations”Lists support common sequence operations:
| Python Expression | Results | Description |
|---|---|---|
len([1, 2, 3]) | 3 | Length: Number of items |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | Concatenation: Creates a new list |
['Hi!'] * 4 | [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] | Repetition: Creates a new list with repeated items |
3 in [1, 2, 3] | True | Membership: Checks if item exists |
for x in [1, 2, 3]: print(x) | 1\n2\n3 | Iteration: Looping through items |
Built-in List Functions & Methods
Section titled “Built-in List Functions & Methods”Python includes functions and methods specifically for lists:
Built-in Functions for Lists:
Section titled “Built-in Functions for Lists:”| Function | Description |
|---|---|
len(list) | Returns the number of items in the list. |
max(list) | Returns the item with the maximum value (items must be comparable). |
min(list) | Returns the item with the minimum value (items must be comparable). |
sum(list) | Returns the sum of items (items must be numeric). |
list(iterable) | Converts an iterable (tuple, string, set, etc.) into a list. |
sorted(list) | Returns a new sorted list (original list unchanged). |
any(list) | Returns True if at least one item in the list is True (or evaluates to True). |
all(list) | Returns True if all items in the list are True (or evaluate to True). |
List Methods (modify the list in-place unless noted):
Section titled “List Methods (modify the list in-place unless noted):”| Method | Description |
|---|---|
list.append(obj) | Adds obj to the end of the list. |
list.extend(iterable) | Appends elements from iterable to the end. |
list.insert(index, obj) | Inserts obj at index. |
list.remove(value) | Removes the first occurrence of value. Raises ValueError if not found. |
list.pop([index]) | Removes and returns item at index (default: last). Raises IndexError if list is empty or index is out of range. |
list.clear() | Removes all items from the list. |
list.index(value[, start[, end]]) | Returns the index of the first occurrence of value. Raises ValueError if not found. |
list.count(value) | Returns the number of times value appears in the list. |
list.sort(key=None, reverse=False) | Sorts the items of the list in-place. key specifies a function to extract comparison key, reverse=True for descending. |
list.reverse() | Reverses the elements of the list in-place. |
list.copy() | Returns a shallow copy of the list. |
Example of sort() vs sorted():
numbers = [3, 1, 4, 1, 5, 9, 2]
# sorted() returns a new listnew_sorted_list = sorted(numbers)print(f"Original list: {numbers}")print(f"New sorted list: {new_sorted_list}")
# sort() modifies the list in-placenumbers.sort(reverse=True) # Sort descendingprint(f"Original list after sort(reverse=True): {numbers}")Output:
Original list: [3, 1, 4, 1, 5, 9, 2]New sorted list: [1, 1, 2, 3, 4, 5, 9]Original list after sort(reverse=True): [9, 5, 4, 3, 2, 1, 1]List Comprehensions (Concise List Creation)
Section titled “List Comprehensions (Concise List Creation)”A powerful and concise way to create lists based on existing iterables.
Syntax: [expression for item in iterable if condition]
# Create a list of squares from 0 to 9squares = [x**2 for x in range(10)]print(f"Squares: {squares}") # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Create a list of even numbers from 0 to 19even_numbers = [x for x in range(20) if x % 2 == 0]print(f"Even numbers: {even_numbers}") # Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Convert list of strings to uppercasewords = ['hello', 'world', 'python']upper_words = [word.upper() for word in words]print(f"Uppercase words: {upper_words}") # Output: ['HELLO', 'WORLD', 'PYTHON']