Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Reordering Existing Lists

00:00 Python offers built-in techniques for both sorting and reversing list objects. For reversal, you have the built-in reversed() function and the .reverse() method of lists. For sorting, you can use the built-in sorted() function as well as the .sort() method of lists.

00:17 Now let’s look at the finer points of using each. Here in the REPL, bring back to life once more our old friend digits, that is, a list of integers from zero to nine.

00:30 We’ll start with reversal using the reversed() function, call reversed(), passing it digits, and the result is a list reverse iterator object.

00:41 This is a kind of iterator that will yield the values of the supplied sequence in reverse order. Because it’s an iterator, its values need to be iterated upon in some way.

00:51 Usually you could use a for loop or a comprehension for this, but maybe you recall a certain way to convert an iterator into a list, maybe one that was mentioned in an earlier lesson.

01:01 Yes, you can use the list() constructor. Call reversed() passing in digits, and pass the result to list().

01:08 And there you go. The list is reversed, going from nine to zero now, and because you use reversed(), the original list object remains unchanged.

01:17 You can look at digits and see it’s still the same. reversed() is useful if you need to perform some operation on the elements of a sequence in reverse order without modifying the original.

01:27 This contrasts with the .reverse() method, so go ahead and call digits.reverse().

01:34 The first thing you might notice, there was no output because the return value of the .reverse() method is None. This is because the .reverse() method mutates the list in place. But examine digits now and see the elements are reversed.

01:50 Probably the biggest source of confusion with these two techniques is that the reversed() function returns a reverse iterator, while the .reverse() method returns None.

01:59 And there’s one more way to reverse a list, and this is my favorite: slicing. Slice digits with the slice [::-1].

02:08 And it returns the reverse, which in this case is the original order. This works because the default arguments for start and stop create a slice that covers the whole list and setting a step size of -1 kind of walks backwards through the list to return the slice, so you get reversal.

02:26 Now let’s look at sorting. Create a list of some random numbers. numbers = [2, 9, 5, 1]. Calling sorted() on an iterable, like a list, will return a list of the items in sorted order.

02:40 With numeric types, the default is ascending order. Try it by calling sorted() and passing in numbers, and they’re sorted. Of course, the original numbers should remain unchanged.

02:53 Yep. [2, 9, 5, 1]. And if you want to get sorted values in descending order, you can use the reverse parameter of sorted().

03:01 To sorted(), pass numbers and the keyword argument, reverse=True.

03:06 And there you go. [9, 5, 2, 1].

03:09 Just like with reversal, there is an in-place method for sorting as well. Call numbers.sort().

03:17 This also returns None and mutates the starting list. Look at numbers again. And now the numbers are sorted with the original ordering lost.

03:25 If you have a list of strings, sorting behavior is actually a little different. Let’s clear the screen. Create a list of strings called words.

03:36 words = ["Writing", "Python", "code", "is", "AWESOME!"], Awesome in all caps for emphasis. Pass words to sorted() and the output ['AWESOME!', 'Python', 'writing', 'code', 'is']. No, the sorted() function doesn’t reorder sentences to make them sound more like a certain Jedi master.

03:57 Actually, Python sorts strings by character based on their Unicode code points. And in the default encoding of UTF-8, this places uppercase letters before lowercase letters, and that’s why you see this particular ordering.

04:11 And you might also wonder, what if I try to sort a mixed list of numerics and strings? Create a list called mixed, populate it with the integer 2, the string "9", the integer 5, and the string "1".

04:24 If you pass this to sorted(), sorted(mixed), you get a TypeError telling you comparison is not supported between these types.

04:32 Because sorting works by comparing elements, you can only sort lists where all elements can be compared with each other.

04:39 Okay, one more example. You can provide your own function to control what Python compares when sorting a list. This is useful when you want to sort a list of more complex objects like tuples or dictionaries.

04:51 Imagine you have a list of database records with information about employees.

04:57 Employees equals a list of tuples of each employee’s name, age, and role. employees = [("John", 30, "designer"),(“Jane”, 28, “engineer”),` ("Bob", 35, "analyst"), ("Mary", 25, "service")].

05:13 If you wanted to sort these tuples by age, you can do the following: call sorted(), passing in employees, and for the keyword argument key, use a lambda function: lambda employee: employee[1], and it’s sorted.

05:30 So how does this work? By passing a function to the key argument, you tell Python to use that function to generate the values used in comparison.

05:38 This particular lambda function retrieves the value of the tuple at index one, which corresponds to the age of the employee, and that’s what ends up being sorted.

05:48 That’s why we see ("Mary", 25) and then ("Jane", 28) and so on.

05:53 And that concludes our tour of rearranging elements in a list. It’s nice that Python provides these tools, but sometimes you just need to work with the elements of a list one at a time.

06:03 So next up, we’re talking about list traversal.

Become a Member to join the conversation.