0

In some code I am modifying I have found the following

data = # np.array with shape (200, 300, 64, 64, 3)
data = np.array([item for obs in data for item in obs])

where item and obs haven't been defined. I am having a hard time wrapping my head around the syntax of the double for-in line. How should I read this?

Toke Faurby
  • 5,788
  • 9
  • 41
  • 62
  • 1
    Write it out like a regular for loop and it should make sense. `for obs in data: for item in obs: print(item)`. The ordering can just be a bit confusing in a list comprehension. – user3483203 Jul 16 '18 at 07:12
  • 1
    It's a list comprehension, and `data` is an iterable of elements that are themselves iterables. Just read it as two nested `for` loops, nested in the same order. – Martijn Pieters Jul 16 '18 at 07:13
  • 1
    @user3483203: I find the order to be entirely logical, it's nesting order from left to right. Add in `if` filtering and it becomes clearer still. What throws people at first is that the innermost loop expression is put before all the loops, but that initial confusion passes quickly. – Martijn Pieters Jul 16 '18 at 07:14
  • Thank you for the clarification. I don't entirely agree with the duplication mark, as it is different list comprehensions, but I get it now, thank you. – Toke Faurby Jul 16 '18 at 07:37

0 Answers0