So i have a question, how can i sort this list:
['Pera','mela','arancia','UVA']
to be like this:
['arancia','mela','Pera','UVA']
In the exercise it said to use the sorted()
function with the cmp argument.
You can easily do that, using the key
argument:
my_list = ['Pera','mela','arancia','UVA']
my_list.sort(key=str.lower)
Which will get your lowercases chars first.
This will change the object in-place and my_list
will be sorted.
You can use sorted
function with the same key
argument as well, if you want to have a new list. For example:
my_list = ['Pera','mela','arancia','UVA']
my_sorted_list = sorted(my_list,key=str.lower)
Output will be:
>>> my_list
['Pera','mela','arancia','UVA']
>>> my_sorted_list
['arancia', 'mela', 'Pera', 'UVA']
You need to sort your elements based lowercase representation of the strings:
sorted(['Pera','mela','arancia','UVA'], key=str.lower)
this will output:
['arancia', 'mela', 'Pera', 'UVA']
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