A list in Python is a mutable, ordered collection of items enclosed in square brackets and separated by commas. Lists can hold any data type-numbers, strings, booleans, or even other lists-and allow changing addition, removal, and modification of elements.
Lists are among the most frequently used data structures in Python. They're ideal for storing sequences of related values, such as a student's grades, a set of coordinates, or a series of API responses. The syntax is straightforward: use square brackets [] and separate items with commas.
For example, creating a list of integers:
temperatures = [72, 68, 75, 80, 77]
This creates a list named temperatures containing five integer values. The list is ordered, meaning the position of each element matters. Accessing the first value uses index 0: temperatures[0] returns 72.
When you write [item1, item2, item3], Python allocates memory for a sequence object and stores references to each item. The list itself is an object with methods like append(), remove(), and sort() that modify its contents in place.
Python evaluates the expression inside the brackets at runtime. This means you can build lists dynamically using expressions, variables, or function calls. For example:
numbers = [x * 2 for x in range(5)] # Creates [0, 2, 4, 6, 8]
This uses a list comprehension-a concise way to generate lists based on existing iterables. The expression x * 2 for x in range(5) runs through numbers 0 to 4, doubles each, and collects the results into a new list.
Lists are mutable, meaning you can change their contents after creation. Unlike tuples, which are immutable, lists support operations like adding elements with append() or replacing values via indexing.
Lists can contain any combination of data types. A single list may include integers, strings, and nested lists. This flexibility makes them suitable for complex data modeling.
| Type | Example | Use Case |
|---|---|---|
| Homogeneous | [1, 2, 3] |
Storing numeric data like sensor readings |
| Heterogeneous | ["Alice", 25, True] |
Representing a person's profile with name, age, and status |
| Nested | [[1, 2], [3, 4]] |
Modeling a grid or matrix in game logic |
| Empty | [] |
Initializing a container for later population |
Creating an empty list is valid and common. You can start with my_list = [] and grow it later using append() or extend().
Using list() as a constructor also creates a list. For example, list("abc") produces ['a', 'b', 'c']. This method is useful when converting strings, ranges, or other iterables into lists.
Many beginners assume that list = [1, 2, 3] creates a copy of the list. It does not. The variable list holds a reference to the list object. Modifying one variable affects others if they share the same reference.
For example:
original = [1, 2, 3]
copy = original
copy.append(4)
print(original) # Output: [1, 2, 3, 4]
Both original and copy refer to the same underlying list. To make a true copy, use slicing: copy = original[:] or copy = list(original).
Another error is confusing lists with tuples. Tuples use parentheses () and are immutable. Using (1, 2, 3) creates a tuple, not a list. Attempting to modify a tuple raises a TypeError.
Python's official documentation states that lists are "ordered collections" that support indexing and slicing. According to the Python Tutorial - Data Structures, lists are designed for frequent insertion and deletion, making them efficient for changing data handling.
Suppose you want to track groceries. Start with an empty list:
groceries = []
Add items using append():
groceries.append("milk")
groceries.append("bread")
groceries.append("eggs")
print(groceries) # Output: ['milk', 'bread', 'eggs']
You can check if an item exists with in:
if "milk" in groceries:
print("Milk is on the list.")
Remove an item with remove():
groceries.remove("bread")
print(groceries) # Output: ['milk', 'eggs']
This workflow mirrors real-world tasks. I built a similar grocery tracker during a weekend project. It helped me avoid buying duplicates and kept my kitchen organized.
Lists are not limited to simple data. You can store dictionaries inside lists to represent multiple users:
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
Accessing Bob's age: users[1]["age"] returns 25.
Understanding how to create a list in Python opens the door to more advanced topics. Once you've created a list, you'll likely want to iterate over it. Use a for loop to process each item:
for item in groceries:
print(f"Buy: {item}")
For deeper control, explore list comprehensions, which combine filtering and transformation in one line. The official tutorial on list comprehensions explains how to filter even numbers from a range:
even_numbers = [n for n in range(10) if n % 2 == 0]
# Result: [0, 2, 4, 6, 8]
Lists are foundational to Python programming. Their ability to store, organize, and modify data makes them essential for scripts, web applications, data analysis, and automation tools.