Taking a nested list input in python

Gulshan
1 min readFeb 19, 2021

--

This post revolves around taking a sub list as input in python

There can be other efficient ways too :)

Taking a sub list as input mean

[[“John”, “23”], [“Ron”, “24”],[“Alice”, “20”]]

There are two ways by which we can achieve this

  1. Using Nested loop (having more complexity)

steps :

  1. Take two list , one for storing sublist and other one for storing elements of sublist
  2. Take a nested loop to take input of final list as well as sublist
  3. after every iteration set the sublist to null
  4. Print the list
x=int(input("enter the size of list"))
y= int(input("enter the size of sublist"))
list1=[]
sublist=[]
for i in range(x):
for j in range(y):
sublist.append(input())
list1.append(sublist)
sublist=[]
print (list1)

2. Without nested loops (this can be used if the elements of the list has not the same type + this has less complexity)

steps:

  1. Take two lists one for storing sublist and other one for storing elements of sublist
  2. Take a loops and start appending the elements onto the list
  3. Set the sublist to null
  4. Print the list
x=int(input ("enter the size of list"))
stu=[]
record=[]
for i in range(0,x):


stu.append(input())
stu.append(input())
record.append(stu)
stu = []

print(record)

Output:

enter the size of list3
John
23
Ron
24
Alice
20
[[‘John’, ‘23’], [‘Ron’, ‘24’], [‘Alice’, ‘20’]]

Any suggesions will be hieghly appreciated.

--

--

Gulshan
Gulshan

Written by Gulshan

A Tech enthusiast who loves to learn

Responses (2)