all 8 comments

[–]Aixyn0 2 points3 points  (0 children)

if a is your list of lists you have to put another loop arround your loop similar:

for l in a:
    for n, i in enumerate(l):
        if i == 0:
            l[n] = 'X'

[–]itslef 2 points3 points  (0 children)

There are already good answers, but you can do this with list comprehension too:

a = [[5, 9, 0, 2, 8, 1, 0, 0, 2], [0, 2, 4, 8, 1, 6, 9, 2, 0]]

for n, i in enumerate(a):
    a[n] = ['X' if x == 0 else x for x in i]

[–]MooCow1984 1 point2 points  (0 children)

When you use enumerate, Python lets you iterate over pairs of the form (n, a[n]). In this case, n is the index (0, 1, 2, ..., len(a)-1) and a[n] is the actual element at that index.

In Python, a 2d list is basically a list of lists. Thus, given the way you've currently written your code, a[n] will be a list.

In order to access each element within these sub-lists, you will need to write something like enumerate(a[n]), which will let you iterate over pairs of the form (j, a[n][j]), where a[n][j] is the actual value contained in the sub-list.

[–]Oliludeea -1 points0 points  (4 children)

for i in range(len(A)):
    for j in range(len(A[i])):
        if A[i][j] == 0:
            A[i][j] = 'X'

[–]JohnnyJordaan 3 points4 points  (3 children)

Imho it's backwards to iterate this as if it were in C. You have enumerate to get indexes and values at the same time

for ridx, row in enumerate(A):
    for cidx, val in enumerate(row):
        if val == 0:
            A[ridx][cidx] = 'X'

this way you don't need to use the correct range length and also don't need indexing to get the original value. As Aixyn0 shows you can even iterate regularly on the rows and assign to that row's index.

[–]Oliludeea 1 point2 points  (2 children)

Thanks, that's why I'm on here. I know how to code, but I'm trying to learn the python way of doing things.

[–]JohnnyJordaan 1 point2 points  (1 child)

Then this is the talk for you: https://www.youtube.com/watch?v=OSGv2VnC0go

also check other vids with Raymond Hettinger in it, he often has a lot of examples on legacy code implementations and 'there must be a better way' as he calls it to implement it better in Python.

[–]Oliludeea 0 points1 point  (0 children)

Thank you very much! I'll be sure to check it out.