In this article, we will cover how to create a list of n-lists in Python.
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python.
The different approaches that we will cover in this article are:
- Using simple multiplication
- Using loop
- Using List comprehension
- Using itertools
Creating a list of n-lists in Python
Example 1: Using simple multiplication
In this example, we are multiplying the list by 4 to get a list of lists.
Python3
# Create a list with 4 references of same sub list lis = [[]] * 4 print (lis) |
Output:
[[], [], [], []]
Example 2: Using List comprehension
In this example, we are using list comprehension for generating a list of lists.
Python3
d1 = [[] for x in range ( 6 )] print (d1) |
Output:
[[], [], [], [], [], []]
Example 3: Using a loop
In this example, we are creating a list using a loop with a range of 6 and appending lists into a list.
Python3
list1 = [] list2 = [] for x in range ( 0 , 5 ): list1.append(list2) print (list1) |
Output:
[[], [], [], [], []]
Example4 : Using itertools
Using the built-in repeat function from the itertools module. This function allows you to repeat a given object a certain number of times, which can be useful for creating lists of lists.
Here is an example of how you can use repeat to create a list of lists in Python:
Python3
from itertools import repeat # Create a list of lists with 5 sub-lists n_lists = list (repeat([], 5 )) print (n_lists) # Output: [[], [], [], [], []] |
[[], [], [], [], []]