How (Not?) to Use Python’s List Comprehensions
From the article:<p><pre><code>  result = [x 
  for sublist in nested_list
      for x in sublist
          if x % 3 == 0
  ]
</code></pre>
I rarely nest comprehensions, but I will occasionally have more than one condition in the filter at the end, or some condition in the selection at the front.<p>Except for the simplest comprehensions, I tend to write mine similar to above, with indents to highlight what part of the comprehension is what.<p>The utility of a comprehension is not so much concise notation. Instead it&#x27;s that a comprehension is an expression (that has an associated value), rather than the for loop which is a statement.<p>Similar to the trinary operator: its advantage is not merely that it replaces an if statement visually, it&#x27;s that it&#x27;s a directly usable expression (that can be composed in a (preferably short) chain of trinaries).<p>This highlights the four things that fizzbuzz requires:<p><pre><code>  print &#x27;\n&#x27;.join([
      &#x27;fizzbuzz&#x27; if x == 0 else
      &#x27;fizz&#x27; if x%3 == 0 else
      &#x27;buzz&#x27; if x%5 == 0 else
      str(x) for x in xrange(1, 101)])
</code></pre>
Gratuitous demo filter conditions:<p><pre><code>  print &#x27;\n&#x27;.join([
      &#x27;fizzbuzz&#x27; if x == 0 else
      &#x27;fizz&#x27; if x%3 == 0 else
      &#x27;buzz&#x27; if x%5 == 0 else
      str(x) for x in xrange(1, 101)
        if x%2 == 0 or x%2 != 0])
</code></pre>
If nested comprehensions make things harder to understand, I&#x27;ll sometimes move an inner comprehension out:<p><pre><code>  subrange = {x for x in range(1, 101)}
  print &#x27;\n&#x27;.join([
      &#x27;fizzbuzz&#x27; if x == 0 else
      &#x27;fizz&#x27; if x%3 == 0 else
      &#x27;buzz&#x27; if x%5 == 0 else
      str(x) for x in subrange
          if x%2 == 0 or x%2 != 0])
</code></pre>
EDIT: OCD forces me to rewrite:<p><pre><code>  subrange = {x for x in range(1, 101)}
  print &#x27;\n&#x27;.join([
      &#x27;fizzbuzz&#x27; if x == 0 else
      &#x27;fizz&#x27; if x%3 == 0 else
      &#x27;buzz&#x27; if x%5 == 0 else
      str(x)
          for x in subrange
              if x%2 == 0 or x%2 != 0])
</code></pre>
FURTHER EDIT: argh!<p><pre><code>  subrange = (x for x in range(1, 101))
</code></pre>
Original was a set comprehension. That it worked &quot;in order&quot; was a happy accident. Further edit is a generator.