Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Do you understand list comprehensions? If so, a generator expression is like a list comprehension, but instead of finding all the items you're interested and packing them into list, it waits, and yields each item out of the expression, one by one.</p> <p>python2 version:</p> <pre><code>&gt;&gt;&gt; my_list = [1, 3, 5, 9, 2, 6] &gt;&gt;&gt; filtered_list = [item for item in my_list if item &gt; 3] &gt;&gt;&gt; print filtered_list [5, 9, 6] &gt;&gt;&gt; len(filtered_list) 3 &gt;&gt;&gt; # compare to generator expression ... &gt;&gt;&gt; filtered_gen = (item for item in my_list if item &gt; 3) &gt;&gt;&gt; print filtered_gen # notice it's a generator object &lt;generator object at 0xb7d5e02c&gt; &gt;&gt;&gt; len(filtered_gen) # So technically, it has no length Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: object of type 'generator' has no len() &gt;&gt;&gt; # We extract each item out individually. We'll do it manually first. ... &gt;&gt;&gt; filtered_gen.next() 5 &gt;&gt;&gt; filtered_gen.next() 9 &gt;&gt;&gt; filtered_gen.next() 6 &gt;&gt;&gt; filtered_gen.next() # Should be all out of items and give an error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; # Yup, the generator is spent. No values for you! ... &gt;&gt;&gt; # Let's prove it gives the same results as our list comprehension ... &gt;&gt;&gt; filtered_gen = (item for item in my_list if item &gt; 3) &gt;&gt;&gt; gen_to_list = list(filtered_gen) &gt;&gt;&gt; print gen_to_list [5, 9, 6] &gt;&gt;&gt; filtered_list == gen_to_list True &gt;&gt;&gt; </code></pre> <p>python3 version:</p> <p>change <code>next()</code> to <code>__next__()</code></p> <p>Because a generator expression only has to yield one item at a time, it can lead to big savings in memory usage. Generator expressions make the most sense in scenarios where you need to take one item at a time, do a lot of calculations based on that item, and then move on to the next item. If you need more than one value, you can also use a generator expression and grab a few at a time. If you need all the values before your program proceeds, use a list comprehension instead.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload