-3

I have a delta_y value that I do not know if its positive or negative, and I'd like to make a general list comprehension solution for it. So its either gonna be a list of tuples (10, 10), (10, 11)... or (10,10), (10,9)...

I've looked around and I dont understand why this isnt working

dxdy = [(10, 10 + i) for i in range(0, delta_y) if delta_y >= 0 else (10, 10 + i) for i in range(0, delta_y, -1))]

Says that the "else" is invalid syntax

Tried looking on stackoverflow to find why but didnt help

chepner
  • 497,756
  • 71
  • 530
  • 681
Mekaniker
  • 9
  • 2

1 Answers1

2

The if following a generator is not part of a conditional expression; it's just a filter for determining which values of the generator will be considered for use in building the list.

You would use a conditional expression to determine what step-size to use in the call to range.

dxdy = [(10, 10 + i) for i in range(0, delta_y, 1 if delta_y >= 0 else -1)]
chepner
  • 497,756
  • 71
  • 530
  • 681