Creating Lists in Python
Python offers several flexible and expressive ways to create lists. The method you choose often depends on whether your data is known upfront, generated dynamically, or derived from another collection.
1. List Literals: The Direct Approach
The most common and straightforward way to create a list is by enclosing a comma-separated sequence of items in square brackets []
. This is known as a list literal.
A list where all items are of the same type.
Pyground
Create a list of your favorite programming languages.
Expected Output:
My favorite languages: ["Python", "JavaScript", "Rust", "Go"]
Output:
2. The list()
Constructor: Converting Other Types
The built-in list()
constructor can create a list from any iterable object. This is incredibly useful for converting data from other types into a list.
When you pass a string to list()
, it creates a list where each character is an element.
Pyground
Convert the word 'Python' into a list of characters.
Expected Output:
['P', 'y', 't', 'h', 'o', 'n']
Output:
3. List Comprehensions: The Pythonic Way
List comprehensions are a concise and readable way to create lists dynamically. They let you build a new list by applying an expression to each item in another sequence, often in a single line.
The basic syntax is [expression for item in iterable]
.
A list comprehension is often a more elegant alternative to a for
loop.
Pyground
Create a list of the squares of the numbers from 0 to 5.
Expected Output:
With comprehension: [0, 1, 4, 9, 16, 25]\nWith a for loop: [0, 1, 4, 9, 16, 25]
Output:
4. Replication: Initializing a List with a Fixed Value
You can use the multiplication operator *
to create a list by repeating a given element a certain number of times. This is very useful for initializing a list of a fixed size.
Pyground
Create a list that represents a game board with 10 empty slots, initialized to zero.
Expected Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Output:
Warning: Replicating Mutable Objects
Be very careful when using *
with mutable objects (like lists or dictionaries). Replication creates multiple references to the same object, not new copies. Modifying one element will modify all of them.
# Incorrect way to create a nested list
bad_matrix = [[]] * 3
bad_matrix[0].append(1)
print(bad_matrix) # Output: [[1], [1], [1]]
# Correct way
good_matrix = [[] for _ in range(3)]
good_matrix[0].append(1)
print(good_matrix) # Output: [[1], [], []]