Alex Rivera | Logout

Show me some cool python list comprehensions

Asked 2010-05-23T21:37:15.880
15

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).

Edit
Report

1 Answer

10

To do the transpose of a matrix mat:

>>> [list(row) for row in zip(*mat)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
answered 2010-05-23T21:39:16.833

Your Answer