What is the pythonic way to set a maximum length paramter?
Let's say I want to restrict a list of strings to a certain maximum size:
>>> x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo']
>>> maxlen = 3
>>> [i for i in x if len(i) <= maxlen]
['foo', 'bar', 'a']
And I want to functionalize it and allow different maxlen but if no maxlen is given, it should return the full list:
def func1(alist, maxlen):
return [i for i in x if len(i) <= maxlen]
And I want to set the maxlen to the max length of element in alist, so I tried but I am torn between using None
, 0
or -1
.
If I use None
, it would be hard to cast the type later on:
def func1(alist, maxlen=None):
if maxlen == None:
maxlen = max(alist, key=len)
return [i for i in x if len(i) <= maxlen]
And I might get this as the function builds on:
>>> maxlen = None
>>> int(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'NoneType'
>>> type(maxlen)
<type 'NoneType'>
If I use -1, it sort of resolve the int(maxlen)
issues but it's also sort of weird since length should never be negative.
def func1(alist, maxlen=-1):
if maxlen < 0:
maxlen = max(alist, key=len)
return [i for i in x if len(i) <= maxlen]
If I use 0, I face the problem when I really need to return an empty list and set maxlen=0
but then again, if I really need an empty list then I don't even need a function to create one.
def func1(alist, maxlen=0):
if maxlen == 0:
maxlen = max(alist, key=len)
return [i for i in x if len(i) <= maxlen]
(Note: the ultimate task is NOT to filter a list, i.e. (filter(lambda k: len(k) <= maxlen, lst))
but it's an example to ask about the pythonic way to set an integer variable that sets a maximum)
Let's say I want to restrict a list of strings to a certain maximum size:
And I want to functionalize it and allow different maxlen but if no maxlen is given, it should return the full list:
And I want to set the maxlen to the max length of element in alist
To address all these requests, the best answer I can think of is something like this...
def func(lst, ln=None):
if not ln:
return lst
ln = max(ln, len(lst))
return [i for i in lst if len(i) <= ln]
edit:
If it is important to handle negative maximum length (who knows why) or 0 length, then a function like this can be used. (Though I am against duck-typing)
def func(lst, ln=None):
if ln is None:
return lst
elif ln < 1: # handles 0, and negative values.
return []
else:
ln = max(ln, len(lst))
return [i for i in lst if len(i) <= ln]