6

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.

Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44
Doni
  • 75
  • 1
  • 1
  • 6

4 Answers4

6

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']
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44
4

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']
kardaj
  • 1,897
  • 19
  • 19
3

Use sorted() with a key.

>>> mc = ['Pera','mela','arancia','UVA']
>>> sorted(mc, key=str.lower)
['arancia', 'mela', 'Pera', 'UVA']
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
1

This will help you:

>>> words = ['Pera','mela','arancia','UVA']
>>> sorted(words)
['Pera', 'UVA', 'arancia', 'mela']
>>> sorted(words, key=str.swapcase)
['arancia', 'mela', 'Pera', 'UVA']

Hope this helps

Amin Alaee
  • 1,895
  • 17
  • 26