Reputation: 103
I have some code to calculate the width of a grid I have in a 2d array. I would like to calculate the width in a single line using nested loops.
I have tried this:
width = [(row, col) for row in grid for col in row width +=1 break]
Heres the code I know works:
for row in grid:
for col in row:
width += 1
break
I'm very confused as to how to write this on one line, thats if it is even possible. Thanks in advance
Upvotes: 0
Views: 141
Reputation: 463
Just to be sure: we are talking about simple python arrays, right?
Question two: all rows have the same number of columns? The break
command in the working approach would suggest so.
If it's a 'yes' for both questions, you could actually just do something like this:
my_grid = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
print(len(my_grid[0])) # prints '4'
Upvotes: 2