Python list is used to store multiple items in a single variable. Python list is a built-in data type used to store collections of data. Python Lists can be created by using square brackets.
I have shared 4 easy methods to create a Python list with lists.
1. Using append Method
Python list has a built-in append method to add values to an existing list. We can use this method to add a new list as an item of the existing list.
Example
list_of_lists = [] # Initialize an empty list to store the lists
list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]
list_of_lists.append(list_1)
list_of_lists.append(list_2)
list_of_lists.append(list_3)
print(list_of_lists) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
How to Access the Lists Inside Another List?
We can easily get the list inside another list using the index of the list item.
print(list_of_lists[0]) # [1, 2, 3]
print(list_of_lists[0][1]) # 2
2. Using List Comprehension Method
Python list comprehension is a built-in easy way to create lists. In this method, the for
loops and conditional statements are used within the square brackets to create new lists.
Example
list_1 = [1, 2, 3]
list_of_lists = [list_1 for item in range(3)]
print(list_of_lists) # [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
3. Using for Loop
We can also use nested loops to create a list of lists in Python. In this method, we will call the append() method explicitly within for loop.
list_of_lists = []
for i in range(3):
list_of_lists.append([])
for n in range(3):
list_of_lists[i].append(n)
print(list_of_lists) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
4. Creating A New List with Lists Directly
This is the last but very useful method. This method can only be used to create a new list of lists in Python when you know the elements of the new list.
list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]
list_of_lists = [list_1, list_2, list_3]
print(list_of_lists) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]