Python | Initializing multiple lists
Last Updated :
18 Apr, 2023
In real applications, we often have to work with multiple lists, and initialize them with empty lists hampers the readability of code. Hence a one-liner is required to perform this task in short so as to give a clear idea of the type and number of lists declared to be used.
Method #1: Using loops
We can enlist all the required list comma separated and then initialize them with a loop of empty lists.
Python3
# Python3 code to demonstrate
# to initialize multiple lists
# using loop
# using loop
# to initialize multiple lists
list1, list2, list3, list4 = ([] for i in range(4))
# printing lists
print (& quot
The initialized lists are : & quot
)
print (& quot
List 1 : & quot
+ str(list1))
print (& quot
List 2 : & quot
+ str(list2))
print (& quot
List 3 : & quot
+ str(list3))
print (& quot
List 4 : & quot
+ str(list4))
Output:The initialized lists are :
List 1 : []
List 2 : []
List 3 : []
List 4 : []
Time complexity: O(n), where n is the number of lists to be initialized.
Auxiliary space: O(n), where n is the number of lists to be initialized.
Method #2: Using defaultdict() Method
This is a method different and also performs a slightly different utility than the above two methods discussed. This creates a dictionary with a specific name and we have the option to make any number of keys and perform the append operations straight away as they get initialized by the list.
Python3
# Python3 code to demonstrate
# to initialize multiple lists
# using defaultdict()
import collections
# using defaultdict() method
# to initialize multiple lists
# no need to initialize with empty lists
mul_list_dict = collections.defaultdict(list)
mul_list_dict['list1'].append(1)
mul_list_dict['list2'].append(2)
mul_list_dict['list3'].append(3)
mul_list_dict['list4'].append(4)
# printing lists
print (& quot
The initialized lists are : & quot
)
print (& quot
List 1 : & quot
+ str(mul_list_dict['list1']))
print (& quot
List 2 : & quot
+ str(mul_list_dict['list2']))
print (& quot
List 3 : & quot
+ str(mul_list_dict['list3']))
print (& quot
List 4 : & quot
+ str(mul_list_dict['list4']))
Output:The initialized lists are :
List 1 : [1]
List 2 : [2]
List 3 : [3]
List 4 : [4]
Time Complexity: O(n), where n is the length of the input list. This is because we’re using defaultdict() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re using constant additional space.
Method #3: Using * operator:
It does not create independent lists, but variables referring to the same (empty) list!
Python3
# Python3 code to demonstrate
# how not to initialize multiple lists
# using * operator
# to initialize multiple pointers to the same list
list1, list2, list3, list4 = ([], ) * 4
# change only list1
list1.append("hello there")
# printing lists
print (& quot
The initialized lists are all the same: & quot
)
print (& quot
List 1 : & quot
+ str(list1))
print (& quot
List 2 : & quot
+ str(list2))
print (& quot
List 3 : & quot
+ str(list3))
print (& quot
List 4 : & quot
+ str(list4))
Output:The initialized lists are all the same:
List 1 : ["hello there"]
List 2 : ["hello there"]
List 3 : ["hello there"]
List 4 : ["hello there"]
Method #4: Using repeat:
To initialize multiple lists using the repeat method, you can do the following:
Python3
from itertools import repeat
# Initialize 4 lists with empty lists
list1, list2, list3, list4 = map(lambda x: list(x), repeat([], 4))
# You can now use the lists as you normally would
list1.append(1)
list2.append(2)
list3.append(3)
list4.append(4)
print(list1) # [1]
print(list2) # [2]
print(list3) # [3]
print(list4) # [4]
#This code is contributed by Edula Vinay Kumar Reddy
The time complexity of this method is O(n), where n is the number of lists you want to create.
Method 5: use a dictionary with list values to store the lists.
This method allows for easy access to the lists using their keys and avoids the need to create four separate variables. It can be particularly useful when dealing with a large number of lists or when the number of lists is not known beforehand.
Python3
lists = {'list1': [], 'list2': [], 'list3': [], 'list4': []}
lists['list1'].append(1)
lists['list2'].append(2)
lists['list3'].append(3)
lists['list4'].append(4)
print(lists['list1']) # [1]
print(lists['list2']) # [2]
print(lists['list3']) # [3]
print(lists['list4']) # [4]
Time complexity: O(1), so the total time complexity of the four operations is also O(1).
Auxiliary space: O(1) because the size of the dictionary does not depend on the size of the input data.
Similar Reads
Python Initialize List of Lists
A list of lists in Python is often used to represent multidimensional data such as rows and columns of a matrix. Initializing a list of lists can be done in several ways each suited to specific requirements such as fixed-size lists or dynamic lists. Let's explore the most efficient and commonly used
3 min read
Python - Interleave multiple lists of same length
When we interleave multiple lists, we mix the items from each list so that they alternate in a new sequence. This is often done when we have lists of the same length and want to combine them, with each item from each list appearing one after another. In this article, we will explore interleaving mul
2 min read
Python - K Matrix Initialization
Sometimes in the world of competitive programming, we need to initialise the matrix, but we donât wish to do it in a longer way using a loop. We need a shorthand for this. This type of problem is quite common in dynamic programming domain. Letâs discuss certain ways in which this can be done. Method
5 min read
Append Multiple items to List - Python
Appending items to a list in Python is an essential and common operation when working with different data structures. Sometimes, we need to add more than one item to a list at a time and in this article, we will explore the various ways to append multiple items to a list at the same time.Using exten
2 min read
Python - Append Multiple Lists at Once
Our task is to merge multiple lists into a single list by appending all their elements. For example, if the input is a = [1, 2], b = [3, 4], and c = [5, 6], the output should be [1, 2, 3, 4, 5, 6].Using itertools.chain()itertools.chain() function from the itertools module is another way to combine l
4 min read
Boolean list initialization - Python
We are given a task to initialize a list of boolean values in Python. A boolean list contains elements that are either True or False. Let's explore several ways to initialize a boolean list in Python.Using List MultiplicationThe most efficient way to initialize a boolean list with identical values i
2 min read
Merge Multiple Lists into one List
In this article, we are going to learn how to merge multiple lists into one list. extend() method is another simple way to merge lists in Python. It modifies the original list by appending the elements of another list to it. This method does not create a new list but instead adds elements to an exis
3 min read
Python - Multiply Two Lists
We are given two list we need to multiply given two list. For example, we are having two lists a = [1, 2, 3] b = [4, 5, 6] we need to multiply list so that the resultant output should be [4, 10, 18].Using a LoopWe can multiply two lists element-wise using a loop by iterating over both lists and mult
2 min read
How To Combine Multiple Lists Into One List Python
Combining multiple lists into a single list is a common operation in Python, and there are various approaches to achieve this task. In this article, we will see how to combine multiple lists into one list in Python. Combine Multiple Lists Into One List PythonBelow are some of the ways by which we ca
2 min read
Python - Pair iteration in list
Pair iteration involves accessing consecutive or specific pairs of elements from a list. It is a common task particularly in scenarios such as comparing neighboring elements, creating tuple pairs, or analyzing sequential data. Python provides several ways to iterate through pairs efficiently ranging
2 min read