Creating a max function from scratch (python) - Stack Overflow
79-character column limit is a nightmare
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?
Is max() an in-built function in Python?
What is the use of the max() and min() functions in Python?
What is the difference between the Python max() and min() functions?
You've got one line of code backwards. Your if statement is effectively saying that if item is greater than Max, set item to Max. You need to flip that to say if item is greater than Max, set Max to item.
if item > Max:
Max = item
return Max
Also, I'm not an expert in Python, but i think you need to change the List inside your function to match the parameter name, in this case args.
*args = list of arguments -as positional arguments
You are passing a list as an argument here. So your code should look something like this -
def maximum(nums):
Max = 0
for item in nums:
if item > Max:
Max=item
return Max
List = [1,5,8,77,24,95]
print maximum(List)
This would give you the result : 95.
On the other hand you can use the max built in function to get the maximum number in the list.
print max(List)