The Wayback Machine - https://web.archive.org/web/20240902160310/https://www.geeksforgeeks.org/python-initializing-multiple-lists/
Open In App

Python | Initializing multiple lists

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Output

[1]
[2]
[3]
[4]

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]


Output

[1]
[2]
[3]
[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

Initializing dictionary with Empty Lists in Python
In Python, it's common to encounter scenarios where you need to store lists in a dictionary. Often, this involves checking if a key exists and then creating a list for that key. However, a more efficient approach is to initialize the dictionary keys with empty lists from the start. Let's explore some methods to accomplish this. How to Initialize a
5 min read
Python | Initializing dictionary with list index values
While working with dictionaries, we might come across a problem in which we require to attach each value in list with it's index, to be used afterwards to solve question. This technique is usually very useful in competitive programming domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using dictionary comprehension
5 min read
Python | Initializing dictionary with list index-values
While working with Python we might need to perform tasks in which we need to assign a dictionary with list values as dictionary values and index as dictionary keys. This type of problem is quite common in cases we need to perform data-type conversion. Let's discuss certain ways in which this task can be performed. Method #1 : Using dictionary compr
4 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Python | Interleave multiple lists of same length
Given lists of the same length, write a Python program to store alternative elements of given lists in a new list. Let's discuss certain ways in which this can be performed. Interleave Multiple Lists of Same Length using Map() and list comprehension In Python, we can interleave multiple lists of the same length using map() and list comprehension. T
8 min read
Python | Intersection of multiple lists
Given two list of lists, write a Python program to find the intersection between the given two lists. Examples: Input : lst1 = [['a', 'c'], ['d', 'e']] lst2 = [['a', 'c'], ['e', 'f'], ['d', 'e']] Output : [['a', 'c'], ['d', 'e']] Input : lst1 = [[1, 5, 7], [2, 3], [6, 9], [4, 8]] lst2 = [[9, 3], [2, 3], [6, 9]] Output : [[2, 3], [6, 9]] Approach #1
5 min read
Python - Elements frequency count in multiple lists
Sometimes while working with Python lists we can have a problem in which we need to extract the frequency of elements in list. But this can be added work if we have more than 1 list we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension + set() + count() This is one of the way in which
6 min read
Python - List of tuples to multiple lists
In this article, we will discuss how to convert a List of tuples to multiple lists. We can convert list of tuples to multiple lists by using the map() function Syntax: map(list, zip(*list_of_tuples) Example: Input: [('a', 'b', 'c'), (1,2,3), ('1','3','4')] Output: ['a', 'b', 'c'], [1, 2, 3], ('1', '3', '4') Example 1: Python code to display a list
3 min read
Python | Append multiple lists at once
There can be an application requirement to append elements of 2-3 lists to one list in Python. This kind of application has the potential to come into the domain of Machine Learning or sometimes in web development as well. In this article, we will learn about Python Append Multiple Items to List at Once. Example: Input: list1 = [1, 3, 5, 5, 4] list
8 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 can see how we can combine multiple lists into one l
2 min read
Convert List of Tuples To Multiple Lists in Python
Managing data often entails working with tuples of information, particularly when working with datasets. For more easy processing, these tuples can sometimes need to be split up into numerous lists. In this article, we will see how to convert list of tuples to multiple lists in Python. Convert List of Tuples to Multiple Lists in PythonBelow are som
3 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
How to create a PySpark dataframe from multiple lists ?
In this article, we will discuss how to create Pyspark dataframe from multiple lists. ApproachCreate data from multiple lists and give column names in another list. So, to do our task we will use the zip method. zip(list1,list2,., list n) Pass this zipped data to spark.createDataFrame() method dataframe = spark.createDataFrame(data, columns) Exampl
2 min read
Merge Multiple Lists into one List
Python lists are versatile data structures that allow the storage of multiple elements in a single variable. While lists provide a convenient way to manage collections of data. In this article, we are going to learn how to merge multiple lists into One list. Merge Multiple Lists Into One List in PythonBelow are some of the ways by which we can merg
3 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python - Interleave two lists of different length
Given two lists of different lengths, the task is to write a Python program to get their elements alternatively and repeat the list elements of the smaller list till the larger list elements get exhausted. Examples: Input : test_list1 = ['a', 'b', 'c'], test_list2 = [5, 7, 3, 0, 1, 8, 4] Output : ['a', 5, 'b', 7, 'c', 3, 'a', 0, 'b', 1, 'c', 8, 'a'
3 min read
Python | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read
Python | Check whether two lists are circularly identical
Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 1
5 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python Program to Split the Even and Odd elements into two different lists
In this program, a list is accepted with a mixture of odd and even elements and based on whether the element is even or odd, it is Split the Even and Odd elements using Python. Examples Input: [8, 12, 15, 9, 3, 11, 26, 23] Output: Even lists: [8, 12, 26] Odd lists: [15, 9, 3, 11, 23] Input: [2, 5, 13, 17, 51, 62, 73, 84, 95] Output: Even lists: [2,
2 min read
Python | Find missing and additional values in two lists
Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements o
3 min read
Python program to find common elements in three lists using sets
Prerequisite: Sets in Python Given three arrays, we have to find common elements in three sorted lists using sets. Examples : Input : ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] Output : [80, 20] Input : ar1 = [1, 5, 5] ar2 = [3, 4, 5, 5, 10] ar3 = [5, 5, 10, 20] Output : [5] Method 1: We have given
5 min read
Practice Tags :