2

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

2 Answers 2

3

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]]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.