Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: treating a scalar as a one element list

Tags:

python

list

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?

like image 204
Shai Avatar asked Feb 16 '23 06:02

Shai


1 Answers

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.

like image 136
Daniel Gratzer Avatar answered Feb 28 '23 05:02

Daniel Gratzer