FAQ: Working with Lists in Python - Sorting Lists I

#1

This community-built FAQ covers the “Sorting Lists I” exercise from the lesson “Working with Lists in Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Sorting Lists I

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

1 Like
#2

Why does this return none.

Please explain more in detail why things print what they do. I feel some of the explanations are very light hearted.

Sorting Lists I

Exercise 4

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

sorted_cities = cities.sort()
print(sorted_cities)

#4

if you need more explanation, you can always check the documentation:

https://docs.python.org/2/tutorial/datastructures.html

.sort() modifies the original list and returns None

#5

If we wanted to save a sorted list as a variable, how would we go about that if sorted_list = list.sort() then print(sorted_list) returns ‘None?’

#6

because .sort() modifies the original list, so you can just do:

my_list = [6, 5, 4]
my_list.sort()
print(my_list)

otherwise, use the sorted() function, which returns a new sorted list (so then you have two lists)

3 Likes
#7

So I was curious about this too. I reckoned that I could make a copy of the original list before sorting it:

Exercise 4

cities = [‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]
unsorted_cities = cities
cities.sort()
print (cities)
print(unsorted_cities)

But that yielded:
[‘London’, ‘Los Angeles’, ‘New York’, ‘Paris’, ‘Rome’]
[‘London’, ‘Los Angeles’, ‘New York’, ‘Paris’, ‘Rome’]

So I moved the print instruction:
cities = [‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]
unsorted_cities = cities
print(unsorted_cities)
cities.sort()
print (cities)

and this produced:
[‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]
[‘London’, ‘Los Angeles’, ‘New York’, ‘Paris’, ‘Rome’]

But I still wondered how to get sorted to print before unsorted, because it looks as though Python is updating unsorted_cities even though it has passed it in the code (is that actually what happens?!).

So I decided to try ensuring that unsorted_cities was actually a list:

cities = [‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]
unsorted_cities = list(cities)
print(unsorted_cities)
cities.sort()
print (cities)
print(unsorted_cities)

which worked, and returned
[‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]
[‘London’, ‘Los Angeles’, ‘New York’, ‘Paris’, ‘Rome’]
[‘London’, ‘Paris’, ‘Rome’, ‘Los Angeles’, ‘New York’]

But I don’t know why. Does anyone?

#8

you have two variables pointing to the same list in memory. Using list() will actually ensure a copy of the list

#9

In general how do I know whether functions will modify my original object or just return the result of it’s operation.

What are each of these types of functions called?
a) sorted(object)
b) object.sort()

By that logic, why doesn’t object.count(‘x’) also modify the object?

the course only explains by saying one comes before and other after… What do I need to search for when studying?

#10

if you have written the function yourself, you will know. If its an existing function or method, you will have to check the documentation

why would count need to modify anything?

the problem is that understanding the differences between methods and functions, you need to understand classes, which will come later

#11

Though reading again and again the solution of exercise 1 & 2 about addresses, I cannot clarify how this solution came up. For example, why ‘1600 Pennsylvania Ave’ is sorted before '221 B Baker St. and then the ‘742 Evergreen Terrace’ follows ? Which criterion was used , either numerical or alphabetical?
Additionally, to extend my previous question, when a list contains items which are not individually categorised as numbers or strings but they are actually “mixed” (like addresses), how does .sort() work?
I read in the lesson, the top question (and answer) about the way sort() function work if a list contains different data types, however I am asking something slightly different as I refer to different data types “inside” each item.

1 Like
Https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/lessons/use-python-list/exercises/sort
#12

Think of every printable character as being ordered from lowest to highest. As we can see, Upper case comes before lower case,

A => 65
a => 97

Numbers are also printable characters that precede the alpha letters.

0 => 48
9 => 57

Sorting follows left to right, ascending (in the normal sense). ‘0’ will come before ‘A’, ‘1’ before ‘7’, &c.

1600 -> 221 -> 742

The criterion used is as we described, ordinal.

2 Likes
#13

When applied to the list of addresses, the sort function orders them in a way that is not alphabetical. Why? What logic does the sorted order follow?

1 Like
#14

Please show us the order in which they were sorted.

#16

See mtf’s previous post: Note that all uppercase letters are “less” than all lowercase letters. Digits and punctuation have their own ranges. If you need your code to alphabetize a list according to a strict schema, you must take those things into account; Python’s “lexicographical order” by itself won’t do it for you…

1 Like
#17

Sorting is pretty straightforward regarding numbers. With words, lexicographical order is complicated a bit concerning comparison between uppercase and lowercase letters, as @patrickd314 has mentioned.

Ideally, addresses should be implemented as a class. Then, a __lt__ method could be defined for that class, and that would determine the sorting order. See Data model: object. __lt__ ( self , other ).

As a simple extension of the current exercise, we could define a key function to govern the sorting order of the addresses. We can sort by the street name first, then by house number. See Sorting HOW TO. Following is an example:

# enhanced addresses list
addresses = ['123 Downing St.',
             '17 Downing St.',
             '221 B Baker St.',
             '42 Wallaby Way',
             '42 Wallaby Ave',
             '12 Grimmauld Place',
             '742 Evergreen Terrace',
             '1600 Pennsylvania Ave',
             '10 Downing St.']

def address_key_maker(address):
    # defines key for addresses list sorting order
    first_space_index = address.index(" ")
    number_str = str(address[:first_space_index])
    street = address[first_space_index + 1:].lower()
    return (street, int(number_str))

# sort addresses list, using the key
addresses.sort(key=address_key_maker)

# demonstrate how addresses list was sorted
for address in addresses:
    print(address)

Output:

221 B Baker St.
10 Downing St.
17 Downing St.
123 Downing St.
742 Evergreen Terrace
12 Grimmauld Place
1600 Pennsylvania Ave
42 Wallaby Ave
42 Wallaby Way

There is still a complication here. In 221 B Baker St., the house number should really be 221 B, but the code places that first B within the name of the street. Implementing an Address class that explicitly breaks the address into components could rectify that issue, as well as bring other geographic entities into the address.

2 Likes