I wrote this and its working fine with everything but when I have an empty list
in a given list(given_list=[[],1,2,3]
) it saying index is out of range. Any help?
If you're confident that there will only be one level of nesting in there, you could do something like
def r_max(lst):
new_lst = []
for i in lst:
try:
new_lst.extend(i)
except TypeError:
new_lst + [i]
return max(new_lst)
But I'm not in love with that solution - but it might inspire you to come up with something nicer.
Two things I'd like to highlight about this solution, in contrast to yours:
type(largest) == type([])
, etc.) isn't considered idiomatic Python. It works, but one of the key points of Python is that it promotes duck typing/EAFP, which means that you should be more concerned with what an object can do (as opposed to what type it is), and that you should just try stuff and recover as opposed to figuring out if you can do it.max
. If you can make your input a non-nested list, then max
does the rest for you.