<p>When should you use generator expressions and when should you use list comprehensions in Python?</p>

<pre><code># Generator expression
(x*2 for x in range(256))

# List comprehension
[x*2 for x in range(256)]
</code></pre>

[{'answer_id': 47792, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 7, 'selected': False, 'text': '<p>Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.</p>\n\n<p>See <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="noreferrer">Generator expressions and list comprehensions</a> for more info.</p>\n'}, {'answer_id': 47793, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 8, 'selected': False, 'text': '<p>Iterating over the <em>generator expression</em> or the <em>list comprehension</em> will do the same thing. However, the <em>list comprehension</em> will create the entire list in memory first while the <em>generator expression</em> will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.</p>\n'}, {'answer_id': 47826, 'author': 'Eli Courtwright', 'author_id': 1694, 'author_profile': 'https://Stackoverflow.com/users/1694', 'pm_score': 9, 'selected': True, 'text': '<p><a href="https://stackoverflow.com/a/47792/4518341">John\'s answer</a> is good (that list comprehensions are better when you want to iterate over something multiple times).  However, it\'s also worth noting that you should use a list if you want to use any of the list methods.  For example, the following code won\'t work:</p>\n\n<pre><code>def gen():\n    return (something for something in get_some_stuff())\n\nprint gen()[:2]     # generators don\'t support indexing or slicing\nprint [5,6] + gen() # generators can\'t be added to lists\n</code></pre>\n\n<p>Basically, use a generator expression if all you\'re doing is iterating once.  If you want to store and use the generated results, then you\'re probably better off with a list comprehension.</p>\n\n<p>Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.</p>\n'}, {'answer_id': 53255, 'author': 'Jacob Rigby', 'author_id': 5357, 'author_profile': 'https://Stackoverflow.com/users/5357', 'pm_score': 2, 'selected': False, 'text': '<p>Sometimes you can get away with the <em>tee</em> function from <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer">itertools</a>, it returns multiple iterators for the same generator that can be used independently.</p>\n'}, {'answer_id': 189840, 'author': 'Chuck', 'author_id': 23788, 'author_profile': 'https://Stackoverflow.com/users/23788', 'pm_score': 6, 'selected': False, 'text': "<p>The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once.  Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.</p>\n\n<p>For example:</p>\n\n<pre><code>sum(x*2 for x in xrange(256))\n\ndict( (k, some_func(k)) for k in some_list_of_keys )\n</code></pre>\n\n<p>The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)</p>\n\n<p>You should, though, use list comprehensions when the desired final product is a list.  You are not going to save any memeory using generator expressions, since you want the generated list.  You also get the benefit of being able to use any of the list functions like sorted or reversed.</p>\n\n<p>For example:</p>\n\n<pre><code>reversed( [x*2 for x in xrange(256)] )\n</code></pre>\n"}, {'answer_id': 22858478, 'author': 'tylerl', 'author_id': 86060, 'author_profile': 'https://Stackoverflow.com/users/86060', 'pm_score': 6, 'selected': False, 'text': '<p>The important point is that the list comprehension creates a new list. The generator creates a an iterable object that will "filter" the source material on-the-fly as you consume the bits.</p>\n\n<p>Imagine you have a 2TB log file called "hugefile.txt", and you want the content and length for all the lines that start with the word "ENTRY".</p>\n\n<p>So you try starting out by writing a list comprehension:</p>\n\n<pre><code>logfile = open("hugefile.txt","r")\nentry_lines = [(line,len(line)) for line in logfile if line.startswith("ENTRY")]\n</code></pre>\n\n<p>This slurps up the whole file, processes each line, and stores the matching lines in your array. This array could therefore contain up to 2TB of content. That\'s a lot of RAM, and probably not practical for your purposes.</p>\n\n<p>So instead we can use a generator to apply a "filter" to our content. No data is actually read until we start iterating over the result.</p>\n\n<pre><code>logfile = open("hugefile.txt","r")\nentry_lines = ((line,len(line)) for line in logfile if line.startswith("ENTRY"))\n</code></pre>\n\n<p>Not even a single line has been read from our file yet. In fact, say we want to filter our result even further:</p>\n\n<pre><code>long_entries = ((line,length) for (line,length) in entry_lines if length &gt; 80)\n</code></pre>\n\n<p>Still nothing has been read, but we\'ve specified now two generators that will act on our data as we wish.</p>\n\n<p>Lets write out our filtered lines to another file:</p>\n\n<pre><code>outfile = open("filtered.txt","a")\nfor entry,length in long_entries:\n    outfile.write(entry)\n</code></pre>\n\n<p><em>Now</em> we read the input file. As our <code>for</code> loop continues to request additional lines, the <code>long_entries</code> generator demands lines from the <code>entry_lines</code> generator, returning only those whose length is greater than 80 characters. And in turn, the <code>entry_lines</code> generator requests lines (filtered as indicated) from the <code>logfile</code> iterator, which in turn reads the file.</p>\n\n<p>So instead of "pushing" data to your output function in the form of a fully-populated list, you\'re giving the output function a way to "pull" data only when its needed. This is in our case much more efficient, but not quite as flexible. Generators are one way, one pass; the data from the log file we\'ve read gets immediately discarded, so we can\'t go back to a previous line. On the other hand, we don\'t have to worry about keeping data around once we\'re done with it.</p>\n'}, {'answer_id': 34599335, 'author': 'Murphy', 'author_id': 4909533, 'author_profile': 'https://Stackoverflow.com/users/4909533', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m using the <a href="https://github.com/michaelfairley/mincemeatpy" rel="nofollow noreferrer">Hadoop Mincemeat module</a>. I think this is a great example to take a note of:</p>\n\n<pre><code>import mincemeat\n\ndef mapfn(k,v):\n    for w in v:\n        yield \'sum\',w\n        #yield \'count\',1\n\n\ndef reducefn(k,v): \n    r1=sum(v)\n    r2=len(v)\n    print r2\n    m=r1/r2\n    std=0\n    for i in range(r2):\n       std+=pow(abs(v[i]-m),2)  \n    res=pow((std/r2),0.5)\n    return r1,r2,res\n</code></pre>\n\n<p>Here the generator gets numbers out of a text file (as big as 15GB) and applies simple math on those numbers using Hadoop\'s map-reduce. If I had not used the yield function, but instead a list comprehension, it would have taken a much longer time calculating the sums and average (not to mention the space complexity).</p>\n\n<p>Hadoop is a great example for using all the advantages of Generators.</p>\n'}, {'answer_id': 35964024, 'author': 'freaker', 'author_id': 1555083, 'author_profile': 'https://Stackoverflow.com/users/1555083', 'pm_score': 4, 'selected': False, 'text': '<p>When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:</p>\n\n<pre><code>&gt;&gt;&gt; mylist = ["a", "b", "c"]\n&gt;&gt;&gt; gen = (elem + "1" for elem in mylist)\n&gt;&gt;&gt; mylist.clear()\n&gt;&gt;&gt; for x in gen: print (x)\n# nothing\n</code></pre>\n\n<p>If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.</p>\n'}, {'answer_id': 62709748, 'author': 'kevin_theinfinityfund', 'author_id': 8419574, 'author_profile': 'https://Stackoverflow.com/users/8419574', 'pm_score': 4, 'selected': False, 'text': '<p>Python 3.7:</p>\n<p><strong>List comprehensions are faster.</strong></p>\n<p><a href="https://i.stack.imgur.com/laJz8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/laJz8.png" alt="enter image description here" /></a></p>\n<p><strong>Generators are more memory efficient.</strong>\n<a href="https://i.stack.imgur.com/mIcuz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mIcuz.png" alt="enter image description here" /></a></p>\n<p>As all others have said, if you\'re looking to scale infinite data, you\'ll need a generator eventually. For relatively static small and medium-sized jobs where speed is necessary, a list comprehension is best.</p>\n'}, {'answer_id': 65724791, 'author': 'Yilmaz', 'author_id': 10262805, 'author_profile': 'https://Stackoverflow.com/users/10262805', 'pm_score': 2, 'selected': False, 'text': "<p>List comprehensions are eager but generators are lazy.</p>\n<p>In list comprehensions all objects are created right away, it takes longer to create and return the list. In generator expressions, object creation is delayed until request by <code>next()</code>. Upon <code>next()</code> generator object is created and returned immediately.</p>\n<p>Iteration is faster in list comprehensions because objects are already created.</p>\n<p>If you iterate all the elements in list comprehension and generator expression, time performance is  about the same. Even though generator expression return generator object right away, it does not create all the elements. Everytime you iterate over a new element, it will create and return it.</p>\n<p>But if you do not iterate through all the elements generator are more efficient. Let's say you need to create a list comprehensions that contains millions of items but you are using only 10 of them. You still have to create millions of items. You are just wasting time for making millions of calculations to create millions of items to use only 10. Or if you are making millions of api requests but end up using only 10 of them. Since generator expressions are lazy, it does not make all the calculations or api calls unless it is requested. In this case using generator expressions will be more efficient.</p>\n<p>In list comprehensions entire collection is loaded to the memory. But generator expressions, once it returns a value to you upon your <code>next()</code> call, it is done with it and it does not need to store it in the memory any more. Only a single item is loaded to the memory. If you are iterating over a huge file in disk, if file is too big you might get memory issue. In this case using generator expression is more efficient.</p>\n"}, {'answer_id': 70421574, 'author': 'Praise', 'author_id': 12643112, 'author_profile': 'https://Stackoverflow.com/users/12643112', 'pm_score': 1, 'selected': False, 'text': '<p>There is something that I think most of the answers have missed. List comprehension basically creates a list and adds it to the stack. In cases where the list object is extremely large, your script process would be killed. A generator would be more preferred in this case as its values are not stored in memory but rather stored as a stateful function. Also speed of creation; list comprehension are slower than generator comprehension</p>\n<p>In short;\nuse list comprehension when the size of the obj is not excessively large else use generator comprehension</p>\n'}, {'answer_id': 70735656, 'author': 'JayS', 'author_id': 1812942, 'author_profile': 'https://Stackoverflow.com/users/1812942', 'pm_score': 0, 'selected': False, 'text': '<p>For functional programming, we want to use as little indexing as possible.  For this reason, If we want to continue using the elements after we take the first slice of elements, islice() is a better choice since the iterator state is saved.</p>\n<pre><code>from itertools import islice\n\ndef slice_and_continue(sequence):\n    ret = []\n    seq_i = iter(sequence) #create an iterator from the list\n\n    seq_slice = islice(seq_i,3) #take first 3 elements and print\n    for x in seq_slice: print(x),\n\n    for x in seq_i: print(x**2), #square the rest of the numbers\n\nslice_and_continue([1,2,3,4,5])\n</code></pre>\n<p>output:  1 2 3 16 25</p>\n'}, {'answer_id': 73214760, 'author': 'Karl Knechtel', 'author_id': 523612, 'author_profile': 'https://Stackoverflow.com/users/523612', 'pm_score': 1, 'selected': False, 'text': '<p>Some notes for built-in Python functions:</p>\n<p>Use a generator expression if you need to <a href="https://stackoverflow.com/questions/17246388">exploit the short-circuiting behaviour of <code>any</code> or <code>all</code></a>. These functions are designed to stop iterating when the answer is known, but a list comprehension must evaluate every element before the function can be called. (<code>any</code> and <code>all</code> will still stop checking elements for <a href="https://stackoverflow.com/questions/39983695/">truthiness</a> when they have the answer, given a list from a list comprehension; however, this is usually trivial compared to the work of actually computing the elements.)</p>\n<p>Generator expressions are of course more memory efficient where they can be used. List comprehensions will be <em>slightly</em> faster with the non-short-circuiting <code>min</code>, <code>max</code> and <code>sum</code> (timings for <code>max</code> shown here):</p>\n<pre><code>$ python -m timeit &quot;max(_ for _ in range(1))&quot;\n500000 loops, best of 5: 476 nsec per loop\n$ python -m timeit &quot;max([_ for _ in range(1)])&quot;\n500000 loops, best of 5: 425 nsec per loop\n$ python -m timeit &quot;max(_ for _ in range(100))&quot;\n50000 loops, best of 5: 4.42 usec per loop\n$ python -m timeit &quot;max([_ for _ in range(100)])&quot;\n100000 loops, best of 5: 3.79 usec per loop\n$ python -m timeit &quot;max(_ for _ in range(10000))&quot;\n500 loops, best of 5: 468 usec per loop\n$ python -m timeit &quot;max([_ for _ in range(10000)])&quot;\n500 loops, best of 5: 442 usec per loop\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/47789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4883/']