简体   繁体   中英

I want to print all the element added in list but it is only printing the last element.(Python)

n = int(input())

for x in range(0,n):
    a = []
    y = int(input())
    a.insert(x,y)
print(a)   

I don't know what I am doing wrong.

You must initialize a once for all before the loop:

n = int(input())
a = []
for x in range(0,n):
    y = int(input())
    a.insert(x,y)
print(a)   

Having a initialization inside the loop overwrites the value of the array in each iteration, starting it outside of the loop will get you the expected result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM