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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

When Not to Use a List Comprehension in Python

00:00 List comprehensions are useful and can help you write elegant code that’s easy to read and debug, but they’re not the right choice for all circumstances.

00:09 For example, they might make your code run more slowly or use more memory. If your code is less performant or harder to understand, then it’s probably better to choose an alternative. Firstly, we need to watch out for nested comprehensions.

00:24 Comprehensions can be nested to create combinations of lists, dictionaries, and sets within a collection. For example, say a climate laboratory is tracking the high temperature in five different cities for the first week in June.

00:38 The perfect data structure for storing this data could be a Python list comprehension nested within a dictionary comprehension. You create the outer collection temps with a dictionary comprehension.

00:51 The expression is a key-pair value, which contains yet another comprehension.

00:57 This code will quickly generate a list of data for each city in cities.

01:03 Nested lists are a common way to create matrices, which are often used for mathematical purposes.

01:11 Let’s take a look at another code block for this. The outer list comprehension [... for _ in range(6)] creates six rows, while the inner list comprehension [i for i in range(5)] fills each of these rows with values.

01:27 So far, the purpose of each nested comprehension is pretty intuitive. However, there are situations, such as flattening nested lists, where the logic arguably makes your code more confusing.

01:40 Take this example, which uses a nested list comprehension to flatten a matrix. The code to flatten the matrix is concise, but it may not be so intuitive to understand how it works. On the other hand, if you were to use for loops to flatten the same matrix, then your code will be much more straightforward.

02:01 Now you can see that the code traverses one row of the matrix at a time, pulling out all the elements in that row before moving on to the next one. While the single-line list comprehension might seem more Pythonic, what’s most important is to write code that your team can easily understand and modify.

02:19 When you choose your approach, you’ll have to make a judgment call based on whether you think the comprehension helps or hurts readability.

02:28 Okay, let’s look at why we should choose generators for large data sets. A list comprehension in Python works by loading the entire output list into memory.

02:38 For small or even medium-sized lists, this is generally fine.

02:43 If you want to sum the squares of the first one thousand integers, then a list comprehension will solve this problem admirably. But what if you wanted to sum the squares of the first billion integers?

02:54 If you try it on your machine, you might notice that your computer becomes non-responsive. That’s because Python is trying to create a list with one billion integers, which consumes more memory than your computer would like. Your computer may not have the resources it needs to generate an enormous list and store it in memory.

03:13 If you do try to do it anyway, then your machine could slow down or even crash. When the size of a list becomes problematic, it’s often helpful to use a generator instead of a list comprehension in Python.

03:26 A generator doesn’t create a single large data structure in memory, but instead returns an iterable. Your code can ask for the next value from the iterable as many times as necessary or until you’ve reached the end of your sequence, while only storing a single value at a time.

03:43 If you were to sum the first billion squares with a generator, then your program will likely run for a while, but it shouldn’t cause your computer to freeze.

03:53 I’ve run this on my machine and I’ve sped up the video for simplicity, but it did run for a few minutes before it completed.

04:00 You can tell that this is a generator because the expression isn’t surrounded by brackets or curly braces. Optionally, generators can be surrounded by parentheses.

04:11 This example still requires a lot of work, but it performs the operations lazily. Because of lazy evaluation, values are only calculated when they’re explicitly requested.

04:22 After the generator yields a value—for example, 567 multiplied by 567it can add that value to the running sum and then discard that value and generate the next value, 568 by 568.

04:36 When the sum() function requests the next value, the cycle starts over. This process keeps the memory footprint small.

04:46 The map() function also operates lazily, meaning that memory won’t be an issue if you choose to use it in this case. Once again I’ve sped up the video, but this just ran for a few minutes on my machine before it completed.

05:00 So, which approach is faster? Should you use list comprehensions or one of their alternatives? Rather than adhere to a single rule that’s true in all cases, it’s more useful to ask yourself whether or not performance matters in your specific circumstance. If not, then it’s usually best to choose whatever approach leads to the cleanest code.

05:20 If you’re in a scenario where performance is important, then it’s typically best to profile different approaches and listen to the data. timeit is a useful library for timing how long it takes chunks of code to run.

05:33 So, let’s use timeit to compare the runtime of map(), for loops, and list comprehensions. Here, you define three methods that each use a different approach for creating a list.

05:45 Then you tell timeit to run each of those functions 100 times each. timeit returns the total time it took to run those 100 executions.

05:56 As the code demonstrates, the biggest difference is between the loop-based approach and map(), with the loop taking 50% longer to execute. Whether or not this matters depends on the needs of your application. It’s up to you whether you prefer the generator expression or map().

06:15 Okay. So now you know when you might want to avoid using a list comprehension in Python. Coming up next, we’ll wrap things up and review everything you’ve learned in this course.

Become a Member to join the conversation.