Python List of Lists

Python List of Lists

Python List of Lists is a Python list containing elements that are Lists.

We know that a Python List can contain elements of any type. So, if we assign Python lists for these elements, we get a Python List of Lists.

Python List of Lists

Python List of Lists is similar to a two dimensional array. Inner lists can have different sizes.

Define Python List of Lists

In the following program, we define list containing lists as elements.

Python Program

list_of_lists = [['a', 25, 69, 'Apple'],
                  [5, 'doll', 854, 41.2],
                  [8, 6, 'car', True]]

print(list_of_lists)
Run

Output

[['a', 25, 69, 'Apple'], [5, 'doll', 854, 41.2], [8, 6, 'car', True]]

The type of elements that we store inside the inner list can be independent of others.

Iterate over Python List of Lists

You can use looping statements like while loop, or for loop to iterate over the inner lists.

In the following program, we shall use while loop to iterate over inner lists.

Python Program

list_of_lists = [['a', 25, 69, 'Apple'],
                  [5, 'doll', 854, 41.2],
                  [8, 6, 'car', True]]

i = 0
while i < len(list_of_lists):
    print(list_of_lists[i])
    i += 1
Run

Output

['a', 25, 69, 'Apple']
[5, 'doll', 854, 41.2]
[8, 6, 'car', True]

Also, in the following example, we shall learn how to use for loop to iterate over the inner lists of Python list of lists.

Python Program

list_of_lists = [['a', 25, 69, 'Apple'],
                  [5, 'doll', 854, 41.2],
                  [8, 6, 'car', True]]

for list_i in list_of_lists:
    print(list_i)
Run

Output

['a', 25, 69, 'Apple']
[5, 'doll', 854, 41.2]
[8, 6, 'car', True]

Remove a List from List of Lists

Just like you remove an item from a list, you can remove a list from list of lists.

In the following example, we will use del keyword to remove list at index 1.

Python Program

list_of_lists = [['a', 25, 69, 'Apple'],
                  [5, 'doll', 854, 41.2],
                  [8, 6, 'car', True]]

del list_of_lists[1]

print(list_of_lists)
Run

Output

[['a', 25, 69, 'Apple'], [8, 6, 'car', True]]

Summary

In this tutorial of Python Examples, we learned how to define list of lists in Python, how to traverse the inner lists, how delete a list, etc., with example programs.