Lists
Work with ordered collections
Lists are super versatile in Python. They let you keep a collection of things neatly organized. Think of them as dynamic, ordered containers for your data.
What are lists?
A list is an ordered sequence of elements. You can put anything in a list: numbers, text, or even other lists! It's one of the most fundamental data structures in Python.
Lists are also mutable. This means you can change them after you've created them. You can add items, remove items, or reorder them. This makes lists very flexible for many programming tasks.
Creating lists
You create a list by placing items inside square brackets [], separated by commas. An empty list is just [].
# An empty list
my_empty_list = []
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A mixed list (though it's often best to keep data types consistent)
mixed_list = [1, "hello", True, 3.14]Accessing items
Each item in a list has an index, starting from 0. The first item is at index 0, the second at index 1, and so on. You access items using square brackets after the list name.
my_list = ["red", "green", "blue"]
first_color = my_list[0] # Gets "red"
print(first_color)
second_color = my_list[1] # Gets "green"
print(second_color)You can also use negative indices. The last item is at index -1, the second to last at -2, and so on. This is handy for getting items from the end of the list.
colors = ["red", "orange", "yellow", "green", "blue"]
last_color = colors[-1] # Gets "blue"
print(last_color)
presumably_second_to_last = colors[-2] # Gets "green"
print(presumably_second_to_last)Changing lists
Since lists are mutable, you can change individual items, add new items, or remove existing ones. Let's look at a few common ways.
To change an item, refer to its index and assign a new value.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # "banana" is replaced with "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']List methods
Python lists come with built-in functions, called methods, to perform common operations. Here are a few essential ones.
append(): Adds an item to the end of the list.insert(): Adds an item at a specific index.remove(): Removes the first occurrence of a specified item.pop(): Removes and returns an item at a given index (or the last item if no index is given).sort(): Sorts the list in ascending order.reverse(): Reverses the order of items in the list.
my_shopping_list = ["milk", "eggs"]
my_shopping_list.append("bread")
print(my_shopping_list) # Output: ['milk', 'eggs', 'bread']
my_shopping_list.insert(0, "butter")
print(my_shopping_list) # Output: ['butter', 'milk', 'eggs', 'bread']
my_shopping_list.remove("eggs")
print(my_shopping_list) # Output: ['butter', 'milk', 'bread']
popped_item = my_shopping_list.pop(1) # Removes 'milk'
print(popped_item) # Output: milk
print(my_shopping_list) # Output: ['butter', 'bread']Checking lists
You can easily check the length of a list or if an item exists within it.
Use the len() function to find out how many items are in a list.
items = [10, 20, 30, 40]
num_items = len(items)
print(num_items) # Output: 4To check if an item is present in a list, use the in keyword. It returns True or False.
guests = ["Alice", "Bob", "Charlie"]
if "Alice" in guests:
print("Alice is coming!")
if "David" not in guests:
print("David is not on the list.")Common mistakes
- IndexError: Trying to access an index that is outside the range of the list. Always ensure your index is valid for the list's current size.
- Modifying during iteration: Changing a list while you are looping through it can lead to unexpected behavior. If you need to remove items, consider creating a new list or iterating a copy.
- Confusing
append()andextend():append()adds a single item, whileextend()adds all items from another iterable (like another list) to the current list.
my_numbers = [1, 2, 3]
# Correct way to add another list's items
my_numbers.extend([4, 5])
print(my_numbers) # Output: [1, 2, 3, 4, 5]
# Incorrect usage of append for another list
my_numbers.append([6, 7]) # Adds the list [6, 7] as a single item!
print(my_numbers) # Output: [1, 2, 3, 4, 5, [6, 7]]Practice
Try these exercises to lock in what you just learned.
1nums = [1, 2, 3]23print(nums)
What's next?
Lists are incredibly powerful. As you write more Python code, you'll find yourself using them constantly. Keep practicing by creating lists, modifying them, and using their methods.
Ready for another challenge? Explore list comprehensions for a concise way to create lists, or dive into tuples for ordered, immutable collections!