Search code examples
pythonlistloopsreplaceswap

Python replace elements = key in 2D array


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

Solution

  • 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]]