views:

112

answers:

2

Could you 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: 

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

try: iter(list_or_elem)
except TypeError: iterable = [list_or_elem]
else: iterable = list_or_elem
y = max(y, *iterable)
Alex Martelli
Similar answer here:http://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-a-variable-is-iterable
Brent Nash
A: 

if you are willing to have add flatten function in your code (theres a good one here) which can basically take a list of lists of lists of... and bring it down to a single list, you can do something like

y = max(flatten([y, list_or_elem]))
adi92
ps: if you go for this, add the use the iter_flatten method specified on that page
adi92