Caustic Caustic - 7 months ago 15
Python Question

length of Python list when list has a single value

Okay I concede that I didn't ask the question very well. I will update my question to be more precise.

I am writing a function that takes a list as an argument. I want to check the length of the list so I can loop through the list.

The problem that I have is when the list has only one entry, len(myList) returns the length of that entry (the length of the string) and not the length of the list which should be == 1.

I can fix this if I force the argument to be parsed as a single value list ['val']. But I would prefer my API to allow the user to parse either a value or a list of values.


def myMethod(self,dataHandle, data,**kwargs):

comment = kwargs.get('comment','')

_dataHandle= list()
_data = list()


for i in range(_dataHandle):
# do stuff.

I would like to be able to call my method either by

myMethod('ed', ed.spectra,comment='down welling irradiance')

or by

myMethod(['ed','lu'] , [ed.spectra,lu.spectra] , comments = ['downwelling', upwelling radiance'])

Any help would be greatly appreciated. Might not seem like a big deal to parse ['ed'], but it breaks the consistency of my API so far.


You can ask if your variable is a list:

def my_method(my_var):
    if isinstance(my_var, list):
        for my_elem in my_var:
            # do stuff with my_elem
    else:  # my_var is not iterable
        # do stuff with my_var

EDIT: Another option is to try iterating over it, and if it fails (raises and exception) you assume is a single element:

def my_method(my_var):
        for my_elem in my_var:
            # do stuff with my_elem
    except TypeError:  # my_var is not iterable
        # do_stuff with my_var

The good thing about this second options is that it will work not only for lists, as the first one, but with anything that is iterable (strings, sets, dicts, etc.)