user1397215
user1397215

Reputation: 321

looping over list of lists without nesting too much

So I have a list of lists called a, and I want to save the indices of an item inside that list in a tuple. for example, if a[0][0] = 1, then i would like to save (0,0) and save into that list.

Right now I have the ff code:

z = []
for i in range(0, len(a)):
    for j in range(0, len(a)):
        if a[i][j] == '.':
            y = (i, j)
            z.append(y)

This works perfectly, but I would like to get rid of the nesting, so I was wondering if there was an alternate way of doing this without nesting too deep.

Upvotes: 1

Views: 156

Answers (3)

John La Rooy
John La Rooy

Reputation: 304215

from itertools import product
for i,j in product(range(len(a)), repeat=2):
    ...

Upvotes: 3

machow
machow

Reputation: 1072

You could use a list comprehension:

z = [(ii, jj) for ii, nested in enumerate(a) for jj, val in enumerate(nested) if val == '.']

However, I think your use of for loops is more clear.

Edit: Also, range by default starts at 0.

Upvotes: 1

mkoryak
mkoryak

Reputation: 57958

some bs like this:

 z = ((i,j) for i in range(0, len(a)) for j in range(0, len(a)) if a[i][j] == '.')

i probably messed this one up - no python at home, but the idea is that you want a nested list comprehension with an if

Upvotes: 0

Related Questions