Python list comprehension

Python list comprehension

I use Python list and dict comprehension heavily these days. To ask me to stop using them would be like asking Angus Young to stand up while he plays guitar.

Instead of doing this…


…you can do this:



List comprehension allows you to build a list in a single line and include conditional statements as part of it.

Instead of just storing the list in a variable, you could act on it right away:



I love to be able to remove potential duplicate list entries from the built list before I act on it.



Another handy use is to filter file extensions when using os.walk:



In the example below, we go through attributes and only act on the attributes that are not part of an exclude list of attributes that we have.



Finally, here is how to use the same awesome sauce with dictionaries.



Do you guys have more goodness to share as it relates to list comprehension?
Will this change your lives forever?
Feel free to comment below.

Spread the knowledge

About the Author

Christian Akesson

Facebook Twitter Google+

Senior Technical Artist at Daybreak Games. Maya user since beta 1 in 1999.