List Comprehensions Made Super Easy In Python
List comprehension lets us create a new list based off an old list, and we'll also talk about how to use the key parameter when sorting lists.
Quick Recap
Make Sure you’ve spent an appropriate amount of time on the lists section, and understanding what mutability means. Here is a quick synopsis on it anyways. Lists are a mutable data structure in Python. Mutable means that we can change them once we have created them. A few example of data structures that are immutable are: strings, and tuples, and a few examples of those that are mutable are lists, and dictionaries.
Table of Contents:
List Comprehension
Common Tasks It Can Handle
Sorting Lists & Key
Finishing Remarks
1 - List Comprehension
Another way to create a list from an existing iterable data structure is by using something called a list comprehension. Iterable data structure include things like tuples, lists, dictionaries, etc… Basically, if you can run a simple for loop on it, it’s iterable.
A list comprehension is basically a shorthand for a for loop. You can click here if you would like a recap on loops. Let’s say we had a tuple going from 1 all the way to 10. Now let’s say we wanted to make a list from this tuple, where every single element in the above tuple was squared. One way to approach this problem is to create an empty list, and then use the .append() in a for loop where we are squaring each element in there. Here it is visualized:
Instead of doing it in the manner above, we can use list comprehensions to basically tell Python to apply the i**2 to every single element in abc, and then chuck this into a list. Here it is being visualized using list comprehensions:
Note: We did not have to initialize sqrs as an empty list, nor did we need to spend a bunch of time on formatting the for loop and doing the indentation properly. List comprehensions are great if you want to run a simple function on something that’s iterable.
2 - Common Tasks It Can Handle
List comprehensions are great because they are sort of like mapping. You can use them to take a chunk of data and run some sort of a mapping on it, in order to generate some new data that has 1 underlying function applied to every single element.
Here are a few useful cases where list comprehension can help you out
Grab Only Vowels From A String
If we have a string that says 'Its the time for your annual weenis inspection', and we only wanted to grab elements which were vowels, we can create something like this:
If you wish to run some basic conditional statement in there, you will want to put the conditional statement to the right of the for loop. For a refresher on conditional statements, click here.
Note: if you put your conditional to the right, it means your mapping would only get applied to those that passed the conditional test. What if we wanted something different applied to those that passed the conditional test vs those that failed it. In that case, we’ll have to put the if/else logic to the left side, look at the example below.
Round Valid Prices, Delete Invalid Ones
Let’s say we have a list, and this list is supposed to represent prices that customers paid when they were buying stuff from us. It makes no sense for a customer to pay a negative price when purchasing a product, so any entry that has a negative number is nonsensical, so, let’s remove it. I am aware that we can just use the abs() to convert the number to a positive one, or the negative could just be a refund, but for the sake of simplicity let’s pretend we live in a world where that doesn’t exist.
Let’s make a list called abc = [-4.2,5.4,-7.6,45.4,789.8,-951.9]. Here is what the example looks like visualized:
Applying Custom Functions To Every Element (Mapping)
If we wish to apply 1 function to every single element in a chunk of data to generate some new data, that is called mapping. Let’s say we have a string of some sorts, and we want to apply a custom function to every single element in that string, we can use list comprehension to tackle this as well.
Let’s define abc = 'life is good homie', and we create a custom function that converts 'i' to 'y'. We can chuck this custom function to our abc string via list comprehension, and then later on use .join() to flatten the list to get a string once again.
3 - Sorting Lists & Key
Sorting A List
Lists have an in-built function for sorting them. The function is the .sort(), it sorts all of the elements in the list by alphabetical or numerical order depending on the type of elements in the list. Here is a quick example in action:
Remember, lists are mutable, so we don’t have to do something like abc = abc.sort( ), we can just do abc.sort( ) instead. For a quick refresher on mutability vs immutability, click here.
For those who are curious, Python does it’s sorting by using what’s called the TimSort algorithm. Here is a video that visualizes what’s going on.
You can click here and see what’s going on in the sort algorithm behind the scenes.
Sorting With The Key Parameter
the .sort() has an optional parameter you can use called key. The key parameter asks if you wish to apply a function to every single element in the list FIRST, and THEN sort the list based off the results.
For example, if I wish to sort the list, but by the number of characters each element has instead of the default alphabetical order, I can set key = len in order to tell python to apply the len() function to every single element in the list first, and then sort the list. Here it is below:
Sorting A Nested List, Based Off The Last Element
If we wanted Python to sort a nested list, but instead of sorting like normal, if we wanted it to sort the elements in the bigger list based off the last element in the smaller sub-lists, we can create a custom function that grabs the last element of a list, and then chuck that at the key parameter. Observe:
4 - Finishing Remarks
In conclusion, sometimes the work you want to do on a list may not be as easy as just simply taking a list, and applying 1 simple function to it. Sometimes, you will have to take 1 or 2 extra steps to get the finalized output you are after. List comprehensions, and sorting with the key parameter can help shave off some of that time usage, and can potentially help you keep your code nice and small instead of becoming extremely crowded, as you saw in the first 2 pictures above.