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','')
_data = list()
for i in range(_dataHandle):
# do stuff.
myMethod('ed', ed.spectra,comment='down welling irradiance')
myMethod(['ed','lu'] , [ed.spectra,lu.spectra] , comments = ['downwelling', upwelling radiance'])
You can ask if your variable is a
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): try: 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 (