How to Create a List of N-Lists in Python

How to Create a List of N-Lists in Python

Creating a list of N-lists in Python can be done in a few different ways, depending on what you need. Here are three common methods to achieve this:

1. Using List Comprehension

List comprehension is a concise way to create lists in Python. If you want a list of N empty lists, you can do it like this:

N = 5 # Number of lists list_of_lists = [[] for _ in range(N)] print(list_of_lists) 

This code will create a list containing N empty lists.

2. Using the * Operator

You can also use the * operator. However, you must be cautious with this approach because it creates references to the same list object, which might not be what you intend. Here's how it looks:

N = 5 list_of_lists = [[]] * N print(list_of_lists) 

Note: If you modify one of the inner lists in this structure, all lists will appear to change because they are all references to the same list object.

3. Using a Loop

Another straightforward method is to use a loop:

N = 5 list_of_lists = [] for _ in range(N): list_of_lists.append([]) print(list_of_lists) 

This method also creates N separate empty lists.

Customizing Inner Lists

If you need each inner list to have initial values (e.g., all zeros), you can modify these approaches. For example, using list comprehension:

N = 5 # Number of lists M = 3 # Size of each inner list list_of_lists = [[0] * M for _ in range(N)] print(list_of_lists) 

This creates a list of N lists, each with M zeros.


More Tags

src angular-universal concatenation rtp sdwebimage mysql-error-1452 listviewitem uistoryboardsegue axios-cookiejar-support select-for-update

More Programming Guides

Other Guides

More Programming Examples