.sort method

Python: Lists | Codecademy

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

addresses.sort()
print(addresses)

how come this doesn’t sort the addresses in alphabetical order?

Hi,
because the strings start with numerical values, it uses them to sort first.

hope that helps

1 Like

To build on the previous reply…

See:
https://zetcode.com/python/sort-list/

Docs:
https://docs.python.org/3/library/stdtypes.html#list.sort

And the “How tos”. in docs on the .sort() method for examples:
https://docs.python.org/3/howto/sorting.html?highlight=sort

.sort() takes two keyword arguments–key and reverse. The key is used for sorting and is called once for each record.
So…one way you could sort by the street name is that you can use a key argument & a lambda function in your .sort() by splitting the string and accessing the index of the street in the string, which would be 1 (or -2). Mess around with the index and see how the list is sorted differently each time you change the index.

Ex:

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

addresses.sort(key=lambda x: x.split()[1])
print(addresses)

>>['221 B Baker St.', '10 Downing St.', '742 Evergreen Terrace', '12 Grimmauld Place', '1600 Pennsylvania Ave', '42 Wallaby Way']
2 Likes