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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read