Manan
Manan

Reputation: 434

Appending a list in another list

I don't know how these two things are working, and their outputs. And if there is any better way to do the same work.

Code 1:

A = []
s = []
for i in range(0,int(input())):
    name = input()
    score = float(input())
    s.append(name)
    s.append(score)
    A.append(s)
    s = []
print(A)

Output 1:

[['firstInput', 23.33],['secondInput',23.33]]

Code 2:

A = []
s = []
for i in range(0,int(input())):
    name = input()
    score = float(input()) 
    s.append(name)
    s.append(score)
    A.append(s)
    s.clear()
print(A)

Output 2:

[[],[]]

Upvotes: 3

Views: 850

Answers (4)

Rahul charan
Rahul charan

Reputation: 835

You can use list comprehension to get your result:-

A = [ [ x for x in input("Enter name And score with space:\t").split() ] 
    for i in range(0, int(input("Enter end range:\t")))]
print(A)

Output

Enter end range:    2
Enter name And score with space:    rahul 74
Enter name And score with space:    nikhil 65
[['rahul', '74'], ['nikhil', '65']]

Upvotes: 0

Nikesh Prasad
Nikesh Prasad

Reputation: 51

When you are appending list "A" with list "s", it creates a reference of "s" in "A", that's why whenever you are calling the .clear method on "s" it clears the elements from "A" as well.

In code 1 you are intialising a new list with the same name "s", everything works fine.

In code 2 you are calling the .clear method on "s" which creates a problem.

In order to use code 2 and get the expected result, you can do this:

A = []
s = []
for i in range(0,int(input())):
    name = input()
    score = float(input()) 
    s.append(name)
    s.append(score)
    A.append(s[:])    # It copies the items of list "s"
    s.clear()
print(A)

Or you can do without "s" as answered by BenT.

Upvotes: 0

Ninad Gaikwad
Ninad Gaikwad

Reputation: 4500

That's the expected list behavior. Python uses references to store elements in list. When you use append, it simply stored reference to s in A. When you clear the list s it will show up as blank in A as well. You can use the copy method if you want to make an independent copy of the list s in A.

Upvotes: 1

BenT
BenT

Reputation: 3200

There are better ways to do this, but you don't need list s at all.

A = []

for i in range(0,int(input())):
    name = input()
    score = float(input())

    A.append([name,score])

print(A)

Upvotes: 3

Related Questions