Why You Should Stop Using List Comprehensions in Python
<p>Ok, the title admittedly is a little clickbait; you shouldn’t <strong>completely</strong> stop using list comprehensions in Python. List comprehensions are very commonly used and are a very <em>Pythonic </em>way to perform a wide range of tasks. Especially in simple applications, they’re definitely better than (for example) appending a list of values to a new list with a for loop.</p>
<p>However, when you’re working with large datasets at scale, list comprehensions can become memory hogs and slow down your workflow (or make it crash entirely). Fortunately, there’s a memory-efficient alternative to list comprehensions we can use to avoid this problem.</p>
<p>In this piece, we’ll go through <strong>generator expressions</strong> and how you can use them as an alternative to list comprehensions to optimize your code. Let’s dive in!</p>
<h1>A simple comparison of list vs generator expressions</h1>
<p>You’re probably familiar with list comprehensions already, but let’s run through a quick example of creating a list of squared numbers from 1 to 10.</p>
<pre>
squares = [i**2 for i in range(1, 11)]
print(squares)</pre>
<p>All the above code does is take use the exponent operator to calculate the square of every number in the range 1 to 11 (so from integer numbers 1 to 10) and return them in a list.</p>
<p><a href="https://python.plainenglish.io/why-you-should-stop-using-list-comprehensions-in-python-a6f96f0f6cbd">Visit Now</a></p>