How to take Nested List as input in Python

titan7585 picture titan7585 · Nov 7, 2014 · Viewed 18.8k times · Source

I have to take input from the user in the following format and make a nested list from it. The first line is the number of rows.

3  
Sourav Das 24 M  
Titan Das 23 M  
Gagan Das 22 F  

The nested list should be like :

parentlist = [  
['Sourav', 'Das', '24', 'M']  
['Titan', 'Das', '23', 'M']  
['Gagan', 'Das', '22', 'M']  
]  

I have written the following code :

k = int(raw_input())
parentlist = [[]]
for i in range(0, k):
    str1 = raw_input()
    parentlist[i] = str1.split()

But it gives some index out of bound exception after entering the 2nd row (as shown below). What's wrong in the code for which it is giving this exception ?

3
Sourav Das 24 M
Titan Das 23 M
Traceback (most recent call last):
  File "nested.py", line 5, in <module>
    parentlist[i] = str1.split()
IndexError: list assignment index out of range

(I am new to Python. So point out any other mistakes too if you find any in my code.)

Answer

Jakube picture Jakube · Nov 7, 2014

When your reading the second line, you attempt to store the splitted line into parentlist[1]. But your parentlist has only one element (parentlist[0]).

The solution is to append the list.

k = int(raw_input())
parentlist = []
for i in range(0, k):
    str1 = raw_input()
    parentlist.append(str1.split())