+ 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

29th Jan 2019, 8:19 PM
Shefeek N
5 Respostas
+ 6
Problem is a*= m as all sublists have the same id in memory
29th Jan 2019, 8:54 PM
Hubert Dudek
Hubert Dudek - avatar
+ 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)) :
29th Jan 2019, 9:34 PM
Tibor Santa
Tibor Santa - avatar
+ 2
For instance one way is: m = int(input()) a = [] for i in range(m): a.append([input(), float(input())]) print(a)
29th Jan 2019, 9:11 PM
portpass
0
Hi Hubert, Thanks for your response. Can u suggest a way forward?
29th Jan 2019, 9:07 PM
Shefeek N
0
Thank you guys
29th Jan 2019, 9:58 PM
Shefeek N