1

trying to use if else in a list comprehension expected output is (23.0,23.3,26.0,27.0,0) have tried converting the values to float before diving it with ten but still not worki

    temps= (230,233,260,270,-999)
    new_temps=((temp)/10 if temp != -999 else 0 for temp in temps)
    print(new_temps)

the error I get is <generator object at 0x0000021889021040>

Nayah
  • 13
  • 2

3 Answers3

2

List comprehension is done with [], not (), the latter is actually the notation to create a generator.

To fix that, just change to []:

temps= (230,233,260,270,-999)
new_temps=tuple([(temp)/10 if temp != -999 else 0 for temp in temps])
print(new_temps)

But if you do want to use the generator notation, you could do this as well:

temps= (230,233,260,270,-999)
new_temps=tuple((temp/10 if temp != -999 else 0 for temp in temps))
print(new_temps)
lnogueir
  • 1,647
  • 2
  • 9
  • 18
1

There's no need to build an intermediate list comprehension, you can pass a generator to the tuple function:

temps = (230, 233, 260, 270, -999)
new_temps = tuple(temp / 10 if temp != -999 else 0 for temp in temps)
print(new_temps)
Francisco
  • 10,005
  • 5
  • 34
  • 42
-1

If you need to print it, you have to convert it to a list.

    temps= (230,233,260,270,-999)
    new_temps=list((temp)/10 if temp != -999 else 0 for temp in temps)
    print(new_temps)
Tim Roberts
  • 34,376
  • 3
  • 17
  • 24