1

Do comprehensions need to end with an else, if I am using else if?

examples:

 a = ['tuple' if type(x)==tuple else 'int' if type(x)==int else 'float'
     if type(x)==float for x in [1, 2.5, (5,6), {}]]
print(a)

It won't work and will make expected else after if expression, but this will work:

a = ['tuple' if type(x)==tuple else 'int' if type(x)==int else 'float'
     if type(x)==float else None for x in [1, 2.5, (5,6), {}]]
print(a)

output: ['int', 'float', 'tuple', None] after all I don't want the None there.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Bro885
  • 11
  • 2
  • 3
    The conditional operator is not related to comprehensions. But yes, they have to have an `else` – Barmar Jan 11 '22 at 15:09
  • 1
    That is just the python ternary operator. Also don't use `type(x) == int`, but `isinstance(x, int)` – azro Jan 11 '22 at 15:13
  • Use the generator's filtering option: `for x in [...] if ` – Barmar Jan 11 '22 at 15:13
  • @Barmar then I will need to calculate the things twice? at the end.. in mylist if type(x) in [float, int, list, etc], so any iteration will pass more conditional operators than it needs to. – Bro885 Jan 11 '22 at 15:25
  • 1
    Yes. So it might be better to use a regular loop with `if` statements instead of a list comprehension. – Barmar Jan 11 '22 at 15:26
  • 1
    You're already calculating it multiple times, by using `type(x)` in each conditional expression. With a loop you can assign that to a variable and test it with `if/elif/...` – Barmar Jan 11 '22 at 15:27

0 Answers0