Find and print the largest number in input_list using the reduce function

Find Maximum Value in List in Python

In this article, we will learn to find the maximum value in a list in Python. We will use some built-in functions, simple approaches, and some custom codes as well to understand the logic. Let's first have a quick look over what is a list in Python and how can we find the maximum value or largest number in a list.

reduce() in Python

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module.

Working :

  • At first step, first two elements of sequence are picked and the result is obtained.
  • Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
  • This process continues till no more elements are left in the container.
  • The final returned result is returned and printed on console.




# python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [1, 3, 5, 6, 2, ]
# using reduce to compute sum of list
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))
# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))
Output The sum of the list elements is : 17 The maximum element of the list is : 6

Output:

The sum of the list elements is : 17 The maximum element of the list is : 6

Using Operator Functions



reduce() can also be combined with operator functions to achieve the similar functionality as with lambda functions and makes the code more readable.




# python code to demonstrate working of reduce()
# using operator functions
# importing functools for reduce()
import functools
# importing operator for operator functions
import operator
# initializing list
lis = [1, 3, 5, 6, 2, ]
# using reduce to compute sum of list
# using operator functions
print("The sum of the list elements is : ", end="")
print(functools.reduce(operator.add, lis))
# using reduce to compute product
# using operator functions
print("The product of list elements is : ", end="")
print(functools.reduce(operator.mul, lis))
# using reduce to concatenate string
print("The concatenated product is : ", end="")
print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))
Output The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks

Output

The sum of the list elements is : 17 The product of list elements is : 180 The concatenated product is : geeksforgeeks

reduce() vs accumulate()

Both reduce() and accumulate() can be used to calculate the summation of a sequence elements. But there are differences in the implementation aspects in both of these.

  • reduce() is defined in “functools” module, accumulate() in “itertools” module.
  • reduce() stores the intermediate result and only returns the final summation value. Whereas, accumulate() returns a iterator containing the intermediate results. The last number of the iterator returned is summation value of the list.
  • reduce(fun,seq) takes function as 1st and sequence as 2nd argument. In contrast accumulate(seq,fun) takes sequence as 1st argument and function as 2nd argument.




# python code to demonstrate summation
# using reduce() and accumulate()
# importing itertools for accumulate()
import itertools
# importing functools for reduce()
import functools
# initializing list
lis = [1, 3, 4, 10, 4]
# printing summation using accumulate()
print("The summation of list using accumulate is :", end="")
print(list(itertools.accumulate(lis, lambda x, y: x+y)))
# printing summation using reduce()
print("The summation of list using reduce is :", end="")
print(functools.reduce(lambda x, y: x+y, lis))
Output The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22

Output:

The summation of list using accumulate is :[1, 4, 8, 18, 22] The summation of list using reduce is :22

reduce() function with three parameters

Reduce function i.e. reduce() function works with 3 parameters in python3 as well as for 2 parameters. To put it in a simple way reduce() places the 3rd parameter before the value of the second one, if it’s present. Thus, it means that if the 2nd argument is an empty sequence, then 3rd argument serves as the default one.

Here is an example :(This example has been take from the functools.reduce() documentation includes a Python version of the function:




# Python program to illustrate sum of two numbers.
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value
# Note that the initializer, when not None, is used as the first value instead of the first value from iterable , and after the whole iterable.
tup = (2,1,0,2,2,0,0,2)
print(reduce(lambda x, y: x+y, tup,6))
# This code is contributed by aashutoshjha
Output 15

This article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Find and print the largest number in input_list using the reduce function




Article Tags :
Python

Six ways to find max value of a list in Python

Sometime ago I read similar article on JavaScript, I thought that it would be a nice little challenge to came up with couple of Python solutions on this topic.

The obvious one:

max(arr)

Using builtin max() function is most pythonic and the best solution in 99.5% of cases (I checked! ;)). People new to Python might not know that max() takes iterable or list of arguments, and also a key= keyword argument so we can get something like this:

>>> a = (0,3)
>>> b = (1,2)
>>> c = (2,1)
>>> max(a, b, c, key=lambda x: x[1])
(0,3)

Implementing “min” and “max” with “reduce”

This is the third installment of my “reduce” series of blog posts. For the first, see here, and for the second, see here.

If you have been reading this series, then you know that “reduce” can be used to sum numbers, or to calculate scores. In that sense, “reduce” justifies its name; we’re invoking a function repeatedly on each element of a collection, boiling the collection down to its essense, as defined by our function.

But “reduce” can also be used to to other, more interesting things. One of them, mentioned in the Ruby documentation, isn’t an obvious candidate for beginners with “reduce”, namely implementing “min” and “max”.

In a world without functional programming or reduce, we could implement a “min” function as follows in Ruby:

def mymin(items) output = items[0] # Assume the first item is the smallest items[1..-1].each do |item| # Iterate through all remaining items if item < output output = item # This item is smaller, so keep it end end output # So far, this is the smallest we've seen end

The definition, if you’re somewhat new to Ruby, works as follows: The “min” function takes an enumerable sequence of items. We assume that the first item is the smallest one, simply to make life easier for ourselves. We then iterate over the remaining items,checking to see if the current one is smaller than the current winner. Each iteration thus leaves “output” with its existing value, or replaces it with something smaller.

Now, the above code works just fine — but it’s a bit long and inelegant just to find the minimum value in an enumerable. After all, it should be possible to implement the same algorithm we we used above in the implementation of “mymin”, but somehow more elegantly and concisely.

That’s where “reduce” comes in. We saw in an earlier blog post that when we use “reduce” to sum the numbers in a collection, is sort of like saying ((((1+2)+3)+4)+5). Well, let’s say that we had a function “smaller” that would return the smaller of two numbers. Then, we could use “reduce” in the following way:

smaller(smaller(smaller(smaller(1,2),3),4),5)

Oh, is that hard to read? Yeah, I thought so. So instead, we can do the following:

items.reduce {|smallest, current| smaller(smallest, current) }

Each time “reduce” invokes our block, it keeps the smaller of its two parameters. The first parameter, which I’ve here called “smallest”, contains the smallest value that we’ve seen so far. The second parameter, “current”, contains the current value from the collection.

That one line certainly looks nicer than our original implementation of “mymin”, I think. There’s just one problem: We haven’t defined any “smaller” method! Fortunately, we can use Ruby’s ternaryoperator to have a tiny, one-line if-then-else statement that does the same thing. In other words:

items.reduce {|smallest, current| smallest < current ? smallest : current }

The moment you realize that “reduce” can be used to hold onto only one of the previous values, you begin to see the opportunities and possibilities that it offers. For example, we can find the shortest or longest word in an array of words:

words = 'This is a sample sentence'.split words.reduce {|shortest, current| (shortest.size < current.size) ? shortest : current } => "a" words.reduce {|longest, current| (longest.size > current.size) ? longest : current } => "sentence"

Now, can we do the same thing in Python? The builtin “reduce” function works similarly to Ruby’s Enumerate#reduce, as we’ve seen in previous posts I wrote on the subject. However, the function that we pass to Python’s “reduce” is more limited than a Ruby block, especially if we use a lambda (i.e., anonymous function).

However, we do have a trick up our sleeve: Python provides an analogous version of Ruby’s ternaryoperator, which is meant for precisely these occasions. I generally tell people to avoid this operator completely, because it causes more problems and confusion than necessary, and probably means that you’re doing something that you shouldn’t be in Python. It works as follows:

>>> x = 'a' >>> is_an_a = "yes" if x == 'a' else "no" >>> is_an_a 'yes'

The oddest thing for me about this form of “if” in Python is that the condition is in the middle of the line. It’s not the postfix “if” of Perl and Ruby, and it’s not the prefix “if” that everyone is used to, but something else entirely. And as such, it’s usually a bad idea to have in your code. But right now, it fits perfectly.

Here, then, is a version of “min” in Python, using “reduce”:

>>> items = [5,-5,10,1,100,-20,30] >>> reduce(lambda smallest, current:smallest if (smallest < current) else current, items) -20

And sure enough, we get the lowest value! Next time, we’ll produce even more complex outputs, with more complex data structures.

  • reuven
  • 7 years ago
  • Categories ↓
    • Python
    • Ruby

Python How to Find the Largest Number in a List

Find and print the largest number in input_list using the reduce function

Artturi Jalli

Find and print the largest number in input_list using the reduce function

To find the largest number in a list in Python:

  1. Set the first element as the largest number candidate.
  2. Loop through the list of numbers.
  3. Update the largest number candidate if any number is greater than it.

Here is how it looks in code:

heights = [100, 2, 300, 10, 11, 1000] largest_number = heights[0] for number in heights: if number > largest_number: largest_number = number print(largest_number)

Output:

1000

This is the naive implementation of finding the largest number. But there are also some useful built-in mechanisms you can use.

In this guide, you learn different ways to find the maximum value in a list in Python.

Table of Contents

  • The max() Function — Find the Largest Element of a List
  • Alternative Approaches to Finding the Largest Number in a List
    • Reduce() Function
      • Reduce() with the built-in max() Function
      • Reduce() with a Custom Max Function
      • Reduce() with a Lambda Function
    • Find The Largest Number Using a Heap Queue
  • Conclusion
  • Further Reading