0

Right now I have a mixed list of different types of elements:

mixed_list = [1, 0.5, 0, 3, 'a', 'z']

print max(mixed_list)  # shows z, but would like it to be 3

How can I find the maximum numeric element of the list?

2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by Lardmeister
0

The easiest way is to extablish a temporary list of numeric values ...

mixed_list = [1, 0.5, 0, 3, 'a', 'z']

print max(mixed_list)  # shows z, but would like it to be 3
 
number_list = []
for x in mixed_list:
    if type(x) in (int, float):
        number_list.append(x)
 
print number_list
print max(number_list)  # 3

You can shorten this with a list comprehension ...

mixed_list = [1, 0.5, 0, 3, 'a', 'z']
 
print max([x for x in mixed_list if type(x) in (int, float)])  # 3
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.