1

I am trying to order sub-lists in a list alphabetically and have seen that .sort(key=lambda x: x[0]) works here. Here is my list:

lis = [['. Michels',
        'Lorenzo Petroli',
        'Carlos Arthur Lang Lisba',
        'Fernanda Gusmo de Lima Kastensmidt',
        'Luigi Carro'],
       ['. Snchez', 'M. Rincn'],
       ['A-Nasser Ansari', 'Mohamed Abdel-Mottaleb']]
lis.sort(key=lambda x: x[0])

I now call lis and it appears as if nothing has happened to the first entry:

[['. Michels',
  'Lorenzo Petroli',
  'Carlos Arthur Lang Lisba',
  'Fernanda Gusmo de Lima Kastensmidt',
  'Luigi Carro'],
 ['. Snchez', 'M. Rincn'],
 ['A-Nasser Ansari', 'Mohamed Abdel-Mottaleb']]

which should be

['. Michels',
 'Carlos Arthur Lang Lisba',
 'Fernanda Gusmo de Lima Kastensmidt',
 'Lorenzo Petroli',
 'Luigi Carro'
 ]

right?

Brad
  • 11
  • 2
  • you have to sort every _sublist_ your current implementation only looks at the outer most list, perhaps a loop can solve your issue? you should notice the difference between the linked question and your issue – gold_cy Feb 27 '19 at 12:48

3 Answers3

2

Try this instead:

for e in lis:
  e.sort()

This will sort all elements of your outer list (i. e. each inner list) in-place.

If you need sorted copies, have a look at @Mykola Zotko's answer. Sorting in-place is cheaper, though.

Your approach did this instead: Sort the outer list by the first elements of the inner lists. Unfortunately based on the first elements, the outer list was already sorted ('. Michels' < '. Snchez' < 'A-Nasser Ansari' because the '.' is before all letters in the ASCII code). So nothing was changed by your approach.

Alfe
  • 56,346
  • 20
  • 107
  • 159
2

You can map the function sorted() to each sublist in the list:

list(map(sorted, lis))
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
1

you have list of the list, so simple solution is:

lis = [['. Michels',
        'Lorenzo Petroli',
        'Carlos Arthur Lang Lisba',
        'Fernanda Gusmo de Lima Kastensmidt',
        'Luigi Carro'],
       ['. Snchez', 'M. Rincn'],
       ['A-Nasser Ansari', 'Mohamed Abdel-Mottaleb']]
[sorted(x) for x in lis]

and the result you will have:

[['. Michels',
  'Carlos Arthur Lang Lisba',
  'Fernanda Gusmo de Lima Kastensmidt',
  'Lorenzo Petroli',
  'Luigi Carro'],
 ['. Snchez', 'M. Rincn'],
 ['A-Nasser Ansari', 'Mohamed Abdel-Mottaleb']]

or if you need to sort by some condition you can use the sorted with key, example (will give the same result as first solution):

[sorted(x, key=lambda x:x[0]) for x in lis]
Brown Bear
  • 19,655
  • 10
  • 58
  • 76