4

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

2
  • What's your expected output? Commented Nov 7, 2014 at 15:06
  • I actually need to take input as shown in my question and then sort it according to the "age" like this : stackoverflow.com/questions/409370/… But I am having problem in taking the input from the user. Commented Nov 7, 2014 at 15:08

10 Answers 10

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())
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. Thanks. Being new to Python, I wasn't able to trace how this was going out of bound.
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)]

Comments

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]]

1 Comment

print l is not Python 3
1

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

2 Comments

@? This answer is correct and exhaustive, why the down vote? +1
I was wondering the same. Someone has downvoted the question and some of the answers.
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...

5 Comments

I tried it in this way, but it still gave the same error.
I edited my answer, s/[[]*3]/[[]]*3/, as in Mr. Kozlov's answer.
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...
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.
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?
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.

Comments

0
l=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    l.append([name,score])
print(l)

Comments

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)

1 Comment

It would be helpful to expand on this answer with some explanations.
0
k = int(input())
parentlist = [None]*k
for i in range(0, k):
    str1 = input()
    parentlist[i] = str1.split()
print(parentlist)

1 Comment

Although this code might solve the problem, a good answer should also explain what the code does and how it helps.
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)

1 Comment

Code alone makes for a pretty low quality answer. Could you explain us what your code snippet does?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.