List comprehension: TypeError: 'float' object is not iterable

List comprehension question. I’m parsing a text file with data as shown.

sig1 = 1039.0
sig2 = 1034.0, 1035.0, 1036.0

With a bit of string manipulation I’m checking if sig1 has multiple values, If yes I’m iterating and appending into a list else just consider as a float.(Example variable sig2)

To cast each value in sig2 into Int, I’m using list comprehension as shown below.

i_lst = [int(i) for i in sig2]

The issue I’m facing is sometimes sig2 can have only single value and this will be considered as a float variable rather than a list. This messes up the list comprehension and I get below error.

TypeError: 'float' object is not iterable

How do I overcome this within the list comprehension?

>Solution :

Convert sig2 to a list if it’s a float:

i_lst = [int(i) for i in ([sig2] if isinstance(sig2, float) else sig2)]

Leave a Reply