+ 1
Need help with lists
I am struggling with the concept of lists here Here is my code m = int(input()) a = [[0,0]] a *= m for i in range(m): a[i][0] = input() a[i][1] = float(input()) print(a) But when I input a value every element in the corresponding position of my list gets updated. For eg: If I enter 3 Alice 23.90 [['Alice', 23.9], ['Alice', 23.9], ['Alice', 23.9]] whereas I need it to be [['Alice', 23.9], [0,0], [0,0]] and update the next row accordingly
5 Answers
+ 6
Problem is a*= m as all sublists have the same id in memory
+ 3
The pythonic way to create the list, is using a list comprehension. That way the values will be independent from each other. As opposed to the multiplication, in which case the values just pointed to the same spot of memory.
List comprehension:
a = [[0, 0] for x in range(int(input()))]
a[0][0] = 1
print(a)
Then you can write a loop like:
for i in range(len(a)) :
+ 2
For instance one way is:
m = int(input())
a = []
for i in range(m):
a.append([input(), float(input())])
print(a)
0
Hi Hubert,
Thanks for your response. Can u suggest a way forward?
0
Thank you guys