5

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.)

titan7585
  • 300
  • 1
  • 5
  • 9
  • What's your expected output? – Avinash Raj Nov 07 '14 at 15:06
  • I actually need to take input as shown in my question and then sort it according to the "age" like this : http://stackoverflow.com/questions/409370/sorting-and-grouping-nested-lists-in-python?answertab=votes#tab-top But I am having problem in taking the input from the user. – titan7585 Nov 07 '14 at 15:08

10 Answers10

9

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())
Jakube
  • 3,353
  • 3
  • 23
  • 40
2

Your parentlist is a list with one element. On the second iteration for your for loop, you try to access the second element of parentlist, that causes the IndexError. Lists in Python work different from e.g. arrays in JavaScript or PHP.

What you actually want to do is create an empty list and then append the result of str1.split() to it.

k = int(raw_input())
parentlist = []
for i in range(0, k):
    str1 = raw_input()
    parentlist.append(str1.split())
Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75
2

You should simply use list comprehension as code will be shorter and faster.

k = int(raw_input())
l = []
print [raw_input().split() for i in range(0, k)]
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
2

In Python 3:

l= [[input(), float(input())] for _ in range(int(input()))]
print l

Input:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Output:

[[Harry,37.21],[Berry,37.21],[Tina,37.2],[Akriti,41],[Harsh,39]]
Georgy
  • 12,464
  • 7
  • 65
  • 73
coderaky
  • 21
  • 5
1

You were quite close

k = int(raw_input())
parentlist = []
for i in range(k):
    str1 = raw_input()
    parentlist.append(str1.split())
  • initialize parentlist to an empty list, it is important because later we want to extend it
    • read an input line
    • split the input line -> a list
    • tell the parentlist to append the new list to what it has already got

If you want to go in a bad direction, you can do, similar to your code

parentlist = [[]]*k
for i in range(k):
    parentlist[i] = raw_input().split()

Exercise, find what the syntax [[]]*k stands for...

gboffi
  • 22,939
  • 8
  • 54
  • 85
  • I tried it in this way, but it still gave the same error. – titan7585 Nov 07 '14 at 15:30
  • I edited my answer, `s/[[]*3]/[[]]*3/`, as in Mr. Kozlov's answer. – gboffi Nov 07 '14 at 15:32
  • A bad direction because if you **replace** a list item, as in our discussion, everything is fine, but if you **modify** a list item, strange things are going to happen... Try the following in the interpreter `l = [[]]*5; l[0]=1 ; l[1].append(5)` You've already seen what is `append`, can you tell me what you get by printing `l`? Well, now try `print l` and come back with an explanation of what happened... – gboffi Nov 07 '14 at 20:43
  • It is appending 5 to the unused `l[2]`, `l[3]` and `l[4]` also along with the `l[1]`. So what I understood is that we can use `[[]] * k` format only when we are sure of how many spaces we are going to need. – titan7585 Nov 08 '14 at 02:33
  • Yes, mutating all elements is danger #1, danger #2 well, you found it yourself, you must know how many slots you need and in many cases (eg processing a file) you don't know it in advance, so imho it's better to memorize the idiom that is safer and more general, isn't it? – gboffi Nov 08 '14 at 07:47
0

Size of your parentlist [[]] is 1, where on 0 position empty list. Your code would be work if you put into parentlist k lists:

parentlist = [[]] * k

Or use append instead, but with append additional look up of method name is necessary.

Sergii Kozlov
  • 838
  • 8
  • 11
0
l=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    l.append([name,score])
print(l)
0
scorelist =[] 
n = int(input())
for i in range(n):
    name.append(str(input()))
    score.append(float(input()))

for i in range(n):    
    scorelist.append([name[i],score[i]])

print(scorelist)
Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
0
k = int(input())
parentlist = [None]*k
for i in range(0, k):
    str1 = input()
    parentlist[i] = str1.split()
print(parentlist)
  • Although this code might solve the problem, a good answer should also explain **what** the code does and **how** it helps. – BDL Sep 18 '20 at 09:32
0

You can also use something like this :-


    k = int(input())
    parentlist = []
    for i in range(k):
        parentlist.append([j for j in input().split()])
    
    print(parentlist)

SNEHEL
  • 1