Reputation: 73
Assuming a 2d list exists that has the values
[[0, 0], [1, 0]]
Is there a way to loop through it such to replace every 0 with a 2 (for example) ?
My first approach was as follows but although the value of l was updated, the entry in the list was not. Any ideas?
for k in g:
for l in k:
if not l == 1:
l = 2
Upvotes: 2
Views: 669
Reputation: 205
Assigning values to the loop variables updates their value but does not modify the the original list. To modify the list, you need to reference its elements directly. The code below does this and replaces all 0s in the list with 2s.
l = [[0, 0], [1, 0]]
for i in range(len(l)):
for j in range(len(l[i])):
if l[i][j] == 0:
l[i][j] = 2
Upvotes: 0
Reputation: 195438
You can use list-comprehension:
lst = [[0, 0], [1, 0]]
lst = [[2 if val == 0 else val for val in subl] for subl in lst]
print(lst)
Prints:
[[2, 2], [1, 2]]
Upvotes: 3