0

i need to create 2 output list ( Even numbers and odd number lists) using if else in list comprehensions. i was able to do it with below code but interested to know on how to do it with if else statements.

numbers = [2,12,3,25,624,21,5,9,12]
even_number,odd_number = [x for x in numbers if x%2==0],[x for x in numbers if x%2==1]

output = [2, 12, 624, 12] [3, 25, 21, 5, 9]

Chandrakanth
  • 25
  • 2
  • 5
  • 1
    you can't without abusing list comps as sideeffects - but you can use a simple for loop with if/else to do it "faster" then what above code does. – Patrick Artner Jun 17 '20 at 14:11
  • just for completeness on @PatrickArtner answer, if you initialize both empty lists in advance, you can (but really shouldn't), use `[even_number.append(x) if x%2==0 else odd_number.append(x) for x in numbers]` to "fill them" as a side effect – Adam.Er8 Jun 17 '20 at 14:16
  • 1
    @Adam I thought more along the lines of `[(even,odd)[x%2==0].append(x) for x in numbers]` to make it even more obscure. but still: **You shan't** is the answer. – Patrick Artner Jun 17 '20 at 14:23
  • 1
    @PatrickArtner Awesome actually :O (but `(odd,even)`* or `[x%s==1]`, True is `1` and False is `0` :P) – Adam.Er8 Jun 17 '20 at 14:27

0 Answers0