Lists are one of the most useful data structures in Python. They store an ordered collection of items that can be of different types.
What is a list?
A list is a collection of items enclosed in square brackets []. Items are separated by commas.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [10, "hello", True, 3.14]
Lists maintain order, so the first item added stays first.
You can also create an empty list:
empty_list = []
Accessing elements with indexes
Each item in a list has a position called an index. Indexes start at 0.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry
Use negative indexes to access from the end:
print(fruits[-1]) # cherry (last item)
print(fruits[-2]) # banana
Modifying lists
Lists are mutable, which means you can change items after creation.
Change an item by index:
fruits[1] = "orange"
print(fruits) # ["apple", "orange", "cherry"]
Add items with append():
fruits.append("grape")
print(fruits) # ["apple", "orange", "cherry", "grape"]
Getting the length
Use len() to find how many items a list has:
print(len(fruits)) # 4
Common examples
Work with a list of scores:
scores = [85, 92, 78, 90]
print(scores[0]) # First score: 85
print(scores[-1]) # Last score: 90
scores.append(88)
print(len(scores)) # 5
Common mistake: IndexError
Trying to access an index that does not exist causes an error.
fruits = ["apple", "banana"]
print(fruits[5]) # IndexError: list index out of range
Always check the length with len() if needed, or use valid indexes.
Quick summary
- Create lists with square brackets
[]. - Access items with indexes starting at 0.
- Use negative indexes for the end of the list.
- Modify items directly or use
append()to add new ones. - Use
len()to get the number of items.
Practice creating and modifying lists. They are essential for storing and working with collections of data in Python programs.
Top comments (0)