Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Nested List in Python

Nested List : 

We can create a nested list in Python very easily. It can be done manually as well as dynamically.

Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested loops in Python. 

Example : matrix = [ [ 1, 2, 3,4 ] ]

nested List in Python

Let’s take some examples to understand what nested list comprehensions can do: 

  • We can declare a nested list manually.

Code #1 :

#python Program
#1st method 
ar=[[1,2] , [3,4]] #2*2 matrix 
for i in range(2):
    print(*ar[i],sep=‘ ‘)

Output : 

1 2
3 4
  • We can declare the list with some fixed value or sequence using for loops, but the size of the list will be fixed.

Code #2:

#python Program
#2nd method 
n=4  #row 
m=4 #col 
ar=[[i for i in range(m)] for j in range(n)]  #4*4 matrix

for i in range(n):
    print(*ar[i],sep=‘ ‘)

Output : 

0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
  • We will declare a list, then we will keep adding another list inside the list according to our requirement.

Code #3:

#python Program
#3rd method 
n=4  #row 
m=4 #col 
ar=[]  #4*4 matrix

for i in range(n):
    x=list(map(int,input().split()))
    ar.append(x) 

for i in range(n):
    print(*ar[i],sep=‘ ‘)


Input : 

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16 

Output : 

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Flat a matrix / List 

Code #4 :

#python Program
n=4  #row 
m=4 #col 
ar=[[ (i+j) for i in range(m)] for j in range(n)]  #4

for i in range(n):
    print(ar[i])

#flattend a matrix 
flat=[]
for i in range(n):
    for j in range(m):
        flat.append(ar[i][j]) 
        
print(‘Flat matrix :’, flat)

Output : 

[0, 1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]
Flat matrix : [0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6]