Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
max() and min() in Python
#1
Hello,

If two iterable objects are put
in the max or min function, then the sum of both iterables is calculated and the
iterable with the biggest sum will be outputted.
Thats how I understand how max() and min() works with more then one iterable object

t1 = 2,1,3
t2 = 1,3,1,5

print("Max. Value:", max(t1,t2))
print("Min. Value:", min(t1,t2))
Output:
Max. Value: (2, 1, 3) Min. Value: (1, 3, 1, 5)
I donĀ“t quite understand then why t1 is max and t2 is min
Reply
#2
The tuple values are compared by the first element and then the second element etc.
with
t1 = 2,1,3
t2 = 1,3,1,5
t1 first element is larger the t2 first element

items = ((2, 1, 3), (1, 3, 1, 5), (2, 1, 4), (2, 0, 3), (2, 2, 4), (2, 2, 3))
print(f"Sorted: {sorted(items)}")
print(f"Max. Value: {max(items)}")
print(f"Min. Value: {min(items)}")
Output:
Sorted: [(1, 3, 1, 5), (2, 0, 3), (2, 1, 3), (2, 1, 4), (2, 2, 3), (2, 2, 4)] Max. Value: (2, 2, 4) Min. Value: (1, 3, 1, 5)

If you want the max and min of of both t1 and t2 combined you could unpack them
t1 = 2, 1, 3
t2 = 1, 3, 1, 5

print(f"Max. Value: {max(*t1,*t2)}")
print(f"Min. Value: {min(*t1,*t2)}")
Output:
Max. Value: 5 Min. Value: 1
coder_sw99 likes this post
Reply
#3
Tuples are compared according to lexicographic order.
coder_sw99 likes this post
Reply
#4
Thanks a lot!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020