Friday, January 17, 2025
HomeTechHow to create a list of empty lists - python

How to create a list of empty lists – python

In Python, you can create a list of empty lists using different methods. Here are the most common approaches:

1. Using List Comprehension

This is a concise and Pythonic way to create a list of empty lists:

# Create a list of 5 empty lists
list_of_empty_lists = [[] for _ in range(5)]

print(list_of_empty_lists)
# Output: [[], [], [], [], []]
2. Using Multiplication (Caution with Mutable Objects)

You can also use the multiplication operator *:

# Create a list of 5 empty lists
list_of_empty_lists = [[]] * 5

print(list_of_empty_lists)
# Output: [[], [], [], [], []]

⚠️ Warning: This method creates references to the same empty list. Modifying one of the inner lists will affect all of them:

list_of_empty_lists[0].append(1)
print(list_of_empty_lists)
# Output: [[1], [1], [1], [1], [1]]

3. Using a Loop

If you want to avoid issues with shared references, you can use a loop:

list_of_empty_lists = []
for _ in range(5):
    list_of_empty_lists.append([])

print(list_of_empty_lists)
# Output: [[], [], [], [], []]

Best Practice

Use list comprehension when you want unique empty lists:

list_of_empty_lists = [[] for _ in range(5)]

This ensures each inner list is independent and avoids the pitfalls of shared references.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x