Example HTML page

Nested Lists in Python

We know that a list is a collection of items separated by commas and enclosed within square brackets [ ]. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with index position starting at 0 from the beginning of the list and in case of reverse accessing of list then the index position is -1.

Ex

>>> List=[1,2,”Python”]

>>> List

[1, 2, ‘Python’]

 Now let us have a glance at nested lists.

Nested Lists

A nested list is a list that appears as an element in another list.

Ex 

>>> nested_list=[1,2,3,[“Hi”,4.5],’abc’]

>>> nested_list

[1, 2, 3, [‘Hi’, 4.5], ‘abc’]

 Here the element with index position 3 is a nested list.

Creating a nested list

Creating a nested list is almost similar as creating a list. Here, a list is considered as one of the elements in a nested list.

>>> n_list=[12,52,[“hi”,3.5],7]

>>> n_list

[12, 52, [‘hi’, 3.5], 7]

 Adding elements into a Nested Lists

We can add elements into a list directly as shown in above. In case of nested lists we use append ( ) method to add elements in to it. For the same list we are going to add elements now.

>>> n_list.append([1,2,’orange’])

>>> n_list

[12, 52, [‘hi’, 3.5], 7, [1, 2, ‘orange’]]

 Accessing elements from Nested Lists

We can access the elements from a nested list by using indexing ‘[ ]’. It is illustrated for the same above example.

>>> n_list

[12, 52, [‘hi’, 3.5], 7, [1, 2, ‘orange’]]

>>> n_list[2]

[‘hi’, 3.5]

>>> n_list[2][1]

3.5

>>> n_list[0]

12

Updating a Nested List

The following example describes how to update a list in a nested list.

>>> n_list

[12, 52, [‘hi’, 3.5], 7, [1, 2, ‘orange’]]

>>> n_list[1]=”VMS”

>>> n_list

[12, ‘VMS’, [‘hi’, 3.5], 7, [1, 2, ‘orange’]]

 Deleting elements in a Nested Lists

The following example describes how to delete an element in a nested list.

>>> n_list=[12, ‘VMS’, [‘hi’, 3.5], 7, [1, 2, ‘orange’]]

>>> n_list

[12, ‘VMS’, [‘hi’, 3.5], 7, [1, 2, ‘orange’]]

>>> del(n_list[3])

>>> n_list

[12, ‘VMS’, [‘hi’, 3.5], [1, 2, ‘orange’]]

>>> del(n_list[2])

>>> n_list

[12, ‘VMS’, [1, 2, ‘orange’]]

>>> del(n_list[2][2])

>>> n_list

[12, ‘VMS’, [1, 2]]

Iteration with elements in nested lists

We can iterate through every element in a nested list by using for loops. The below example describes the iteration of an element in nested list.

n_list=[12, 'VMS', ['hi', 3.5], 7]
for i in n_list:
      for item in n_list:
        print(item)
      print( )

Output

12

VMS

[‘hi’, 3.5]

7

 

12

VMS

[‘hi’, 3.5]

7

 

12

VMS

[‘hi’, 3.5]

7

 

12

VMS

[‘hi’, 3.5]

7

 Note

Here the output prints for four times because the elements in the list are 4 in count.

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest