Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

[[],[]]
like image 494
Manan Avatar asked Nov 17 '25 23:11

Manan


2 Answers

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)
like image 51
BenT Avatar answered Nov 20 '25 14:11

BenT


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.

like image 34
Ninad Gaikwad Avatar answered Nov 20 '25 14:11

Ninad Gaikwad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!