Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading