Join Regular Classroom : Visit ClassroomTech

Nested Lists in Python

Lists in python are a very powerful data type used in a broader spectrum of programing. If a list containing another list, in turn may contain another list then it is known as Nested list. Here are a few examples for better understanding:-

list1 = [“c“, “o“, “d“, “e“]

list2 = [“w“, “e“, [“c“, “o“, “d, “e“, “r“]]

list3 = [“w“, “e“, [“c“, “o“, [“d“, “e“]]]

Here,
list1 contain elements but no list within the parent list.
list2 contain a list within the parent list.
list3 contains a list which in turn contains another list.

How to access the nested list items:-

Example 1:

la = [“w“, “e“, [“c“, “o“, “d“, “e“, “r“]]
print(la[2][3])     # to access “e” here

Output:
e

Explanation:
Here, the element is inside a sublist(indexed at 2) has the element “e” at index 3.

Example 2:

lb = [“w“, “e“, [“c“, “o“, [“d“, “e“]]]     
print(lb[2][2][0])     # to access “d” here

Output:

d

Explanation:
Here, the element is inside a sublist(indexed at 2) inside which another sublist(indexed 2) has the element “d” at index 0.

You Missed
Also Checkout