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?

Recommended Answers

All 2 Replies

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

Thank you Vega!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.