Skip to content

Instantly share code, notes, and snippets.

@drocco007
Created March 26, 2014 15:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drocco007/9785632 to your computer and use it in GitHub Desktop.
Save drocco007/9785632 to your computer and use it in GitHub Desktop.

When I need to remember the spelling for a list comprehension with more than one loop in Python, I find the following mnemonic helpful:

write the for statements in the same order you would write a nested loop

For example, suppose we have a nested list that we wish to flatten:

>>> nested_list = [[1, 2, '5!'], (3, 'sir!')]

To flatten this with normal for loop syntax, we would first pull out each sublist, then iterate over each sublist's values:

>>> def flatten(list_):
...     for sublist in list_:
...         for value in sublist:
...             yield value

>>> list(flatten(nested_list))
[1, 2, '5!', 3, 'sir!']

When writing this as a comprehension, the for terms go in the same order as the nested loops:

>>> [value for sublist in nested_list for value in sublist]
[1, 2, '5!', 3, 'sir!']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment