Add list to list of lists Python

How to Create a List of Lists in Python

Last Updated: December 15th, 2021

This article is all about creating and initialize a list of lists in Python. A list of lists basically a nested list that contains one or more lists inside a list. There are many approaches to create a list of lists. Here, we are using the append[] method and list comprehension technique to create a list of lists. After creating a list of lists, we will see to access list elements as well. Let's see some examples.

Create a list of lists using the append[] method in Python

In this example, we are using an append[] method that used to append a list into a list as an element. we created two lists and append them into another list using the append[] method and print the list which is actually a list of lists.

# Take two lists list1 = [1,2,3,4] list2 = [5,6,7,8] list3 = [] # Take an empty list # make list of lists list3.append[list1] list3.append[list2] print[list3]

Output:

[[1, 2, 3, 4], [5, 6, 7, 8]]

Create a list of lists using the list initializerin Python

The list initializer syntax is used to create a list in Python. We can use this technique to create a list of lists by passing lists as elements into the list initializer. See the code and output.

# Take two lists list1 = [1,2,3,4] list2 = [5,6,7,8] # make list of lists list3 = [list1, list2] # Display result print[list3]

Output:

[[1, 2, 3, 4], [5, 6, 7, 8]]

Create a list of lists using for-loop in Python

We can use for loop to create a list of lists in Python. We used the append[] method inside the loop to add the element into the list to form a list of lists. See the code and output.

lists = [] # make list of lists for i in range[2]: # append list lists.append[[]] for j in range[5]: lists[i].append[j] # Display result print[lists]

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Create a list of lists using list comprehensionin Python

If you are comfortable with list comprehension then use it to make a list of lists as we did in the below code example. See the code and output here.

# Take a list list = ['Apple','Mango','Orange'] lists = [] # make list of lists lists = [[val] for val in list] # Display result print[lists]

Output:

[['Apple'], ['Mango'], ['Orange']]

How to access elements froma list of listsin Python

We can access elements by using an index. The list index starts from 0 and end to n-1 where n is the length of the list. Here, we used 0 index to get the first elementof the list.

# Take a list list = ['Apple','Mango','Orange'] lists = [] # make list of lists lists = [[val] for val in list] # Display result print[lists] # Access Element print[lists[0]] print[lists[2]]

Output:

[['Apple'], ['Mango'], ['Orange']]
['Apple']
['Orange']

Video liên quan

Chủ Đề