DEV Community

Zander Bailey
Zander Bailey

Posted on

Getting Sorted Part 2: Python

Last time we talked about sorting in Java, which can be very powerful in it’s own way, but it revolves around the type of data structures native to Java. Python has additional types of structures that can complicate how a collection is structured, so it can be very useful to know how to navigate these structures in a simple manner. Python is commonly used for manipulating large datasets in various formats, which makes it very important to be able to find things when you need them.

If we look at a List in Python, it usually appears very similar to a List in Java, and has similar ways of sorting. First let’s define some lists:

colors = [red,blue,green,Yellow]
numbers = [10,5,35]

Now it’s important to understand the difference between a method that sorts in-place and one that produces sorted output. An in-place sort takes the original collection and re-arranges it so that the original collection is in sorted order. A method that outputs a sorted list creates a new list in sorted order, while the original list remains unchanged. In Python the basic version of this is .sort() and sorted:

sorted_numbers = sorted(numbers)

#numbers: [10,5,35]
#sorted_numbers: [5,10,35]

numbers.sort()
#numbers: [5,10,35]

An important thing to note about sorted is that although it can accept collections similar to a List as input, it will only return the sorted output as a List. A list of strings can be sorted alphabetically by default as well, although it pays attention to case, and places words starting with uppercase letters before lowercase words:

colors.sort()
#colors: [‘Yellow’,’blue’,’green’,’red’]

Now that we’ve covered the basic sorting function, let’s get a little more advanced. When we sorted our numbers array it defaulted to sorting in ascending order. That is, it starts with the lowest number in the first position. But by using the ‘reverse’ parameter we can force it to sort in reverse order:

sorted(numbers, reverse = True)  # = [35,10,5]

Python has very flexible data structures, but that also brings with it the possibility for complications. A Python List can hold multiple data types at a time, like having an integer and a string, or integers and a tuple. The problem with storing dissimilar data types in the same list is that they have no common point of reference for sorting, and an attempt to sort such a list will produce an error.

So far we’ve mostly been talking about sorting Lists, but there are special ways to sort more complex collections as well, like a List of Tuples or a Dictionary. Next time we will discuss how to accomplish this using key and lambda functions.

Top comments (0)