Do not get afraid of the name- list of lists. It is nothing but a list with other lists as an element. In this tutorial, we will learn about the different ways to create List of lists in Python.
Table of contents
- What is a list of lists?
- Using append() function to create a list of lists in Python
- Create a list of lists using the list initializer in Python
- Using list comprehension to create a list of lists
- Using for-loop to create a list of lists in Python
- Closing thoughts
What is a list of lists?
In any programming language, lists are used to store more than one item in a single variable. In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas. It can be used to store integer, float, string and more.
Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element.
Here is an example of a list of lists to make things more clear:
[[a,b],[c,d],[e,f]]
Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.
Now we will discuss different ways to create a list of lists in Python.
Using append() function to create a list of lists in Python
What append() function does is that it combines all the lists as elements into one list. It adds a list at the end of the list.
In order to have a complete understanding of how this functions works, we will create two lists and then using the append() function we will combine them into one list
Input:
# Create 2 independent lists
list_1 = [a,b,c]
list_2 = [d,e,f]
# Create an empty list
list = []
# Create List of lists
list.append(list_1)
list.append(list_2)
print (list)
Output:
[[a,b,c],[d,e,f]]
Create a list of lists using the list initializer in Python
Using a list initializer, we treat lists as elements. We create a list of lists by passing lists as elements. It is the easiest way to create a list of lists.
Input:
# Create 2 independent lists
list_1 = [a,b,c]
list_2 = [d,e,f]
# Create List of lists
list = [list1, list2]
# Display result
print(list)
Output:
[[a,b,c],[d,e,f]]
Using list comprehension to create a list of lists
List comprehension is a bit complicated yet short method to create a list of lists in Python.
Input:
list_1 = [a,b,c]
list = [l1 for i in range(3)]
print(list)
Output:
[[a,b,c],[a,b,c],[a,b,c]]
Using for-loop to create a list of lists in Python
You can use the for-loop to create a list of lists to create too. Here is a code snippet for better understanding.
Input:
list = []
# Create List of list
for i in range(2):
list.append([])
for j in range(3):
list[i].append(j)
print(lst)
Output:
[[a,b,c],[a,b,c]]
Closing thoughts
A list of lists is a list where each element is a list by itself. The List is one of the 4 built-in data types in Python. One can learn more about other Python data types here.
Top comments (0)