Why You Should Stop Using List Comprehensions in Python

<p>Ok, the title admittedly is a little clickbait; you shouldn&rsquo;t&nbsp;<strong>completely</strong>&nbsp;stop using list comprehensions in Python. List comprehensions are very commonly used and are a very&nbsp;<em>Pythonic&nbsp;</em>way to perform a wide range of tasks. Especially in simple applications, they&rsquo;re definitely better than (for example) appending a list of values to a new list with a for loop.</p> <p>However, when you&rsquo;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&rsquo;s a memory-efficient alternative to list comprehensions we can use to avoid this problem.</p> <p>In this piece, we&rsquo;ll go through&nbsp;<strong>generator expressions</strong>&nbsp;and how you can use them as an alternative to list comprehensions to optimize your code. Let&rsquo;s dive in!</p> <h1>A simple comparison of list vs generator expressions</h1> <p>You&rsquo;re probably familiar with list comprehensions already, but let&rsquo;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>