Nested List in Python
Nested Lists
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.
Nested Lists in Python
Python uses the term “nested list” to describe a list inside of another list. Another way to describe a list is as a nested list is one that contains additional lists as its elements.
Example : matrix = [ [ 1, 2, 3,4 ] ]
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]
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Login/Signup to comment