Nested Lists In Python Programing - Coderz*United

Nested Lists In Python Programing



Two dimensional lists

Two dimensional list is a list having all the all its elements as lists of same shapes, ie; Two dimensional list is a lists of lists 

for example: L1 = [ [1,2] , [9,8] , [5,6] ]

Creating a 2D list

To create a 2D list by inputting element by element, you can employ a nested loop as shown in the program below: Ballupur rose and other for reading individual elements of each row.


Ques: Program to create a 2D list ?

 Lst = []

 r = int(input("How many rows ?"))

 c = int(input("How many columns ?"))

 for i in range(r):

     row = []

     for j in range (c):

         elem = int(input("Element"+str(i)+","+str(j)+":"))

         row.append(elem)

     Lst.append(row)

 print("List created is: ",Lst)


Traversing a 2D list

To traverse 2D list element by element can employ a nested loop as earlier:  one loop for row and another loop for traversing individual elements of  each row. 


Ques : Program to traverse a 2D list ?

 Lst = []

 r = int(input("How many rows ?"))

 c = int(input("How many columns ?"))

 for i in range(r):

     row = []

     for j in range (c):

         elem = int(input("Element"+str(i)+","+str(j)+":"))

         row.append(elem)

     Lst.append(row)

 print("List created is: ")

 print("Lst = [ ")

 for a in range(r):

     print("\t[",end ="")

     for b in range(c):

         print(Lst[a][b],end=" ")

     print("]")

 print("\t]")


Changing individual element in a 2D list

You can access individual elements in a 2D list by specifying its indexes in a square brackets.e.g., To access the 3rd row’s 3rd element from the 2D list namely Lst that we created in the previous session you will write:

print ( Lst[2][2] )

Out[1]: 70