Easy to process iterable and no iteration

Could you please let me know how I can optimize the following code?

def f(y, list_or_elem):
  if getattr(list_or_elem, '__iter__'):
    y = max(y, *list_or_elem)
  else:
    y = max(y, list_or_elem)

      

+2


a source to share


2 answers


The best optimization of all would be to avoid the nonsense of taking "either a list or a single item" as an argument. But, if you insist, it's better to use try / except to remove the ASAP anomaly and make what is bound to be iterable:



try: iter(list_or_elem)
except TypeError: iterable = [list_or_elem]
else: iterable = list_or_elem
y = max(y, *iterable)

      

+1


a source


if you want to add an anti-aliasing function to your code (it's a good one here ) that can basically take a list of lists of lists ... and bring it down to a single list, you can do something like



y = max(flatten([y, list_or_elem]))

      

0


a source







All Articles