Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find min & max of two lists

Tags:

python

list

I have two lists such as:

l_one = [2,5,7,9,3]
l_two = [4,6,9,11,4]

...and I need to find the min and max value from both lists combined. That is, I want to generate a single min and a single max value.

My question is - what is the most pythonic way to achieve this?

Any help much appreciated.

like image 503
Darwin Tech Avatar asked Apr 04 '12 14:04

Darwin Tech


People also ask

How do you find the min value in Python?

In Python, you can use min() and max() to find the smallest and largest value, respectively, in a list or a string.

Is there a min function in Python?

Python min() Function The min() function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetically comparison is done.

How do you find the max and min value in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.


2 Answers

Arguably the most readable way is

max(l_one + l_two)

or

min(l_one + l_two)

It will copy the lists, though, since l_one + l_two creates a new list. To avoid copying, you could do

max(max(l_one), max(l_two))
min(min(l_one), min(l_two))
like image 73
Sven Marnach Avatar answered Oct 12 '22 01:10

Sven Marnach


Another way that avoids copying the lists

>>> l_one = [2,5,7,9,3]
>>> l_two = [4,6,9,11,4]
>>> 
>>> from itertools import chain
>>> max(chain(l_one, l_two))
11
>>> min(chain(l_one, l_two))
2
like image 32
John La Rooy Avatar answered Oct 12 '22 01:10

John La Rooy