Show me some cool python list comprehensions
Posted
by christangrant
on Stack Overflow
See other posts from Stack Overflow
or by christangrant
Published on 2010-05-23T21:37:15Z
Indexed on
2010/05/23
21:40 UTC
Read the original article
Hit count: 202
One of the major strengths of python and a few other (functional) programming languages are the list comprehension. They allow programmers to write complex expressions in 1 line. They may be confusing at first but if one gets used to the syntax, it is much better than nested complicated for loops.
With that said, please share with me some of the coolest uses of list comprehensions. (By cool, I just mean useful) It could be for some programming contest, or a production system.
For example:
To do the transpose of a matrix mat
>>> mat = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
>>> [[row[i] for row in mat] for i in [0, 1, 2]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Please include a description of the expression and where it was used (if possible).
© Stack Overflow or respective owner