List.sort

Hello,

addresses = [‘221 B Baker St.’, ‘42 Wallaby Way’, ‘12 Grimmauld Place’, ‘742 Evergreen Terrace’, ‘1600 Pennsylvania Ave’, ‘10 Downing St.’]

Sort addresses here:

addresses.sort()
print(addresses)

Exercise 3

names = [‘Ron’, ‘Hermione’, ‘Harry’, ‘Albus’, ‘Sirius’]
names.sort()

Exercise 4

cities = [‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]

sorted_cities = cities.sort()
print(sorted_cities)

this is the line of code that is accepted and the task is:
Use print to examine sorted_cities . Why is it not the sorted version of cities ?

So they ask you to do something but won’t explain why it’s returning None, which I find rather annoying as this is a pro course and there is too little explaining…
can anyone explain this please?

The in-place sort cannot be assigned. To create a separate, independent sorted list, use the sorted() function, which does support assignment.

sorted_cities = sorted(cities)

This will have no effect on the original list.

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.