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.
In Python, you can use min() and max() to find the smallest and largest value, respectively, in a list or a string.
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.
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.
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With