Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of strings alphabetically

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.

like image 683
Doni Avatar asked Jun 16 '16 11:06

Doni


2 Answers

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']
like image 131
Avihoo Mamka Avatar answered Nov 15 '22 07:11

Avihoo Mamka


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']
like image 31
kardaj Avatar answered Nov 15 '22 08:11

kardaj