Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.
In Python, a list of lists is a list object with each list element being a separate list.
Given the size,
The task is to create and Initialize a list of lists of given size in Python using different methods.
Examples:
Input :
Size=4
Output :
[ [ ] , [ ] , [ ] , [ ] ]
Creating list of lists with the same ID(Not Preferable):
Below is the fastest way to build and initialize a list of lists with the same ID.
# Let us take size as 4 listoflists = [[]]*4 # print the listoflists print("List of Lists : ", listoflists) # Print the ID's of all elements in this listoflists print("ID's : ") for element in listoflists: print(id(element))
Output:
List of Lists : [[], [], [], []] ID's : 140398466447368 140398466447368 140398466447368 140398466447368
Explanation:
Here List of Lists of size 4 is created but we can see all are having same Id. This will result in the list containing the same list object repeated N times and cause referencing errors.
Creating list of lists with the different ID’s:
It is most preferable because all the lists will have different ID’s such that we can access and refer them separately.
There are several ways to create list of lists some of them are:
- Using List Comprehension , range() and Append()
- Using For loop and Append()
- Using Itertools
- Using empty() in Numpy
Method #1: Using List Comprehension , range() and Append()
Using list comprehensions is the most Pythonic way to build an empty list of lists.
This can be accomplished in the following way:
# Driver code # let us take size of list as 4 size = 4 # Creating listoflists using list comprehension listoflists = [[] for i in range(size)] # Printing empty listoflists print("List of Lists :", listoflists) print("ID : ") # Printing the ID's of all sublists for element in listoflists: print(id(element)) # Initializing list of lists # let us initialize element in 2 nd sublist listoflists[1].append(3) # printing list after initialization print("List of Lists :", listoflists)
Output:
List of Lists : [[], [], [], []] ID : 140259187390280 140259187390024 140259187390088 140259187390152 List of Lists : [[], [3], [], []]
Explanation:
Here we created list of lists of size 4, with different IDs for each sublist. Â As a result, we can refer to them and initialise them separately.
We initialized second sublist with element 3.
Method #2 : Â Using For loop and Append()
Let’s say we want to make a list that includes 4 separate sub-lists.
To do so, we’ll first construct a new empty list, then use a for loop to iterate from 0 to 3 and add an empty list
to the new list for each iteration.
Below is the implementation:
# Driver code # let us take size of list as 4 size = 4 # Taking empty listoflists listoflists = [] # Iterate over a sequence of numbers from 0 to size for i in range(size): listoflists.append([]) # Printing empty listoflists print("List of Lists :", listoflists) print("ID : ") # Printing the ID's of all sublists for element in listoflists: print(id(element)) # Initializing list of lists # let us initialize element in 2 nd sublist listoflists[1].append(3) # printing list after initialization print("List of Lists :", listoflists)
Output :
List of Lists : [[], [], [], []] ID : 140629449111368 140629449111240 140629449111304 140629449111176 List of Lists : [[], [3], [], []]
Method #3: Using Itertools
The repeat() function in the itertools module can be used to replace the range() function in the above list comprehension.
Below is the implementation
# import repeat from itertools from itertools import repeat # let us take size of list as 4 size = 4 # Creating listoflists using list comprehension listoflists = [[] for i in repeat(None, size)] # Printing empty listoflists print("List of Lists :", listoflists) print("ID : ") # Printing the ID's of all sublists for element in listoflists: print(id(element)) # Initializing list of lists # let us initialize element in 2 nd sublist listoflists[1].append(3) # printing list after initialization print("List of Lists :", listoflists)
Output:
List of Lists : [[], [], [], []] ID : 140551299438408 140551299438152 140551299438216 140551299438280 List of Lists : [[], [3], [], []]
Method #4 : Using empty() in Numpy
The empty() function in the Numpy module in Python creates an empty Numpy array of a given shape
numpy.empty(shape, dtype=float, order='C')
It creates a new Numpy array of the specified shape.
Now, to generate a list of lists, we’ll use the empty() function to create a 2D Numpy array, which we’ll then transform to a list of lists using the numpy.tolist() function.
Below is the implementation:
# importing numpy module import numpy # let us take size of list as 4 size = 4 # Create a 2D Numpy array of shape (4, 0) and convert it to list of lists listoflists = numpy.empty((size, 0)).tolist() # Printing empty listoflists print("List of Lists :", listoflists) print("ID : ") # Printing the ID's of all sublists for element in listoflists: print(id(element)) # Initializing list of lists # let us initialize element in 2 nd sublist listoflists[1].append(3) # printing list after initialization print("List of Lists :", listoflists)
Note: This method performance is often slower than the list comprehension.
Related Programs:
- python how to create a list and initialize with same values
- python how to create a list of all the keys in the dictionary
- python how to create a list of all the values in a dictionary
- python how to find all indexes of an item in a list
- how to create and add elements in a hashset in java
- what is a structured numpy array and how to create and sort it in python
- python how to get the list of all files in a zip archive