how to find maximum from a list using a for loop in pythonic way?
python - Get max value from a list with lists? - Stack Overflow
min() vs 'sort() and then list[0]'
As others have mentioned, min will be quicker. min just has to walk through the list once, whereas sort must do more compares, making it more complex.
However, one case you might want to use sort is when you need more than just the minimum. Eg. you want the 5 smallest items, not just the smallest. Here "sorted(mylist)[:5]" will do the job, but another option to keep in mind is the heapq module, as "heapq.nsmallest(5, mylist)" will often perform better than sort, at least for a small number of items.
How do I find the relative maximum in a function?
lst = [1,2,3,4,5]
basically, I want to find max: max(lst)
but I want to use a syntax like this: var = max(item) for item in lst
first, why does this return a generator object instead of throwing some error?
And second, how to do it properly?
Edit: so basically there is a function. I need to compute the max value returned by the function. The function should calculate values from a list of inputs.
So, I need to de this:
var = max(func(item)) for item in lst
I just wanted to know if we can do this in one or two liner?
Loop through your outer list and select the last element of each sublist:
def max_value(inputlist):
return max([sublist[-1] for sublist in inputlist])
print max_value(resultlist)
# 9.1931
It's also best if you keep all function related variables in-scope (pass the list as an argument and don't confuse the namespace by reusing variable names).
In perhaps a more functional than pythonic manner:
>>> max(map(lambda x: x[3], resultlist))
9.1931
It begins by mapping each element of result list to the number value and then finds the max.
The intermediate array is:
>>> map(lambda x: x[3], resultlist)
[8.3931000000000004, 6.3231000000000002, 9.1930999999999994]