How Does the Max() Function Work on List of Strings in Python

How does the max() function work on list of strings in python?

This is actually a good question and the answer varies depending on whether you're on python2.x or python3.x ... And which python implementation you're using1.

See here for a description of how python compares different types. The link says pretty much all that you need to know, but as a quick summary:

  • comparison of objects of the same type acts as you'd expect.
  • comparison of objects of different type are ordered by their type name on python2.x and raise an error on python3.x (Unless a custom comparison operator is defined.)
  • old style classes break all the rules but they shouldn't be used anyway.

1Hopefully you can see by the amount of uncertainty there that this is not really well defined and so it's a situation that you should try to avoid.

max value of a list (of string items)

Strings are compared by lexicographical ordering, not by length. S comes after D in the alphabet:

>>> 'Superman' > 'Dudley Do-Right'
True

An inefficient way to replicate what max() does, would be to sort the input sequence and pick the last value for the result. So [20, 10, 8, 15], when sorted, puts 20 last and that's what max() returns. Sorting the strings in Heroes results in Superman being listed last.

If you wanted to find the longest string, use the key argument to max():

max(Heroes, key=len)

Here, instead of comparing values in Heroes directly, max() compares the values by the return value of the key argument; now the value for which len() returns the largest value is returned as the maximum.

Demo:

>>> Heroes = ['Superman', 'Batman', 'Dudley Do-Right', 'Luke Skywalker']
>>> max(Heroes, key=len)
'Dudley Do-Right'

Why is the max() function returning an item that is smaller than another one in a list?

Strings are sorted lexicographically, relative to each other. o comes after a, b, and c. The length isn't a factor unless the strings are identical up to that point, in which case the shorter string is judged as 'less'. max(), then, produces the lexicographically greatest string (i.e. furthest back in the dictionary).

If you want to sort by length, you have to give the max() function a key (for example, the len() function):

>>> my_list = ['apples', 'oranges', 'cherries', 'banana']
>>> print(max(my_list))
oranges
>>> print(max(my_list, key=len))
cherries

Get max length of value inside a list which contains other lists

You could recursively search for all values in your data structure:

data = [{
"name": "title",
"value": "titel{TM} D3",
"is_on_label": 1
},
[{
"name": "title",
"value": "titel{TM} D3",
"is_on_label": 1,
"sub_options": [
{
"value": "30V max 3A",
"id_configuration_v": "1668"
},
{
"value": "none none none none",
"id_configuration_v": "1696"
}
]
}],
{
"name": "DK in",
"value": "24V max 2.5A",
"is_on_label": 1,
"id_configuration": 79,
"options": [{
"value": "30V max 3A",
"id_configuration_v": "1668"
},
{
"value": "none",
"id_configuration_v": "1696"
}
]
}
]

def recur(data, count):
if isinstance(data, list):
for item in data:
count = recur(item, count)
elif isinstance(data, dict):
for k, v in data.items():
if k == 'value':
count.append(len(v))
else:
count = recur(v, count)
return count

result = recur(data, [])
print(max(result))

Out:

19

Python: max(a list of numbers as characters) gives right and wrong answer

As I was writing this question and trying to understand this behavior with max() function, I tried x.sort() and it gave out the answer. So let me paste the sorted list:

['-214', '-3', '-6', '-64', '0', '1', '29', '4', '4', '5', '54', '542', '6']

So basically these are strings and initial character of the string decides its value as string. Meaning, 5kaify will come first than 6kaify .

For more clarity, if I add bunch of alphabets into this list as below:

x=['4', '5', '29', '54', '4', '0','d', '-214', '542', '-64', '1','a', '-3','c', '6', '-6']

max(x) will give 'd' as the answer as alphabetically it would come later than all the strings in the list, hence max() checks for alphabetical order as the value for list of strings/characters and not its integral/numeric value. Hope this was helpful.

Using max() on a list containing strings and integers

In python2, strings and numbers compare in arbitrary but consistent order.

See Comparisons

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result

In python3, this raises a type error.

TypeError: unorderable types: str() > int()

Can someone explain the output of the following code regarding max()?

if you provide max() a string, it returns the highest alphabetical character in a string. So it will order based on alphabetical order descending.

As explained here https://www.geeksforgeeks.org/python-string-max/#:~:text=os._exit()-,Python%20String%20%7C%20max(),alphabetical%20character%20in%20a%20string.&text=Return%20value%3A,highest%20character%20in%20the%20string.



Related Topics



Leave a reply



Submit