George V. Reilly

Python: a use for nested list comprehensions

I wanted to turn a list like ['*.zip', '*.pyc', '*.log'] into ['--exclude', '*.zip', '--exclude', '*.pyc', '--exclude', '*.log'].

A simple list com­pre­hen­sion doesn’t work as desired:

In [1]: excludes = ['*.zip', '*.pyc', '*.log']

In [2]: [('--exclude', e) for e in excludes]
Out[2]: [('--exclude', '*.zip'), ('--exclude', '*.pyc'), ('--exclude', '*.log')]

The trick is to use a nested com­pre­hen­sion:

In [5]: [arg for pattern in excludes
             for arg in ['--exclude', pattern]]
Out[5]: ['--exclude', '*.zip', '--exclude', '*.pyc', '--exclude', '*.log']
blog comments powered by Disqus
Free ebooks from Springer » « Review: The Magician's Land