I am writing a python script that process lists read from a file:
l = readListFromFile( myFile )
for i in l :
# do something to each element
All works fine when l
has more than one element.
However, when there is only one element in the list readFromFile
returns l
as a scalar and not as a list. Hence for i in l
fails with error
object is not iterable
I have no control over readFromFile
, and my question is how can I make python treat l
as a alist even in the case where l
has only a single element?
Well a simple solution is
l = readListFromFile(myFile)
try:
i = iter(l)
if isinstance(l, str):
i = l
except TypeError:
i = [l]
for .... in i
This will work even if you change what readListFromFile
to return another iterable.
A one liner solution if it's guaranteed to be a str
or a list (or other iterable) is just
l = readListFromFile(myFile)
for e in [l] if isinstance(l, str) else l:
just using a ternary operator.
On an aside, having a method called readList... not always returning a list is just evil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With