Understanding List Comprehension Vs Traditional Loop And Build
Solution 1:
List comprehension is simply a way of creating a list based on another list. (Or other iterable item)
For instance, if we have a list a = [1, 2, 5, 7]
, then we could create a list, b
, containing the values of a
doubled in two ways.
Without list comprehensions
b = []
for e in a:
b.append(2*e)
With list comprehensions
b = [2*e for e in a]
There's nothing more to it than that. It's simply a nice syntax for building lists based on lists.
See also:
Solution 2:
The first line is a list comprehension. The rest is not.
return [[row_times_column(m1, i, m2, j) for j in range(len(res[i]))]
for i in range(len(res))]
Solution 3:
The following also uses list comprehension for matrix multiplication
defmatrix_mult(m1, m2):
return [[sum(m1[i][k]*m2[k][j] for k inrange(len(m2))) for j inrange(len(m2[0]))] for i inrange(len(m1))]
Solution 4:
The rationale between list comprehension in Python is explained in PEP 202
List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used.
So there is really no "special trickery" behind the idea. It's just a syntactical extension, to put it as the PEP does.
HTH
Solution 5:
Mark Pilgrim does a much better job at explaining list comprehension than I could in his book Dive into Python. This book is really good for starting out in Python and just a good read in general. Recommended.
P.S.: There's list comprehension for Python 3 as well in Dive into Python 3
Post a Comment for "Understanding List Comprehension Vs Traditional Loop And Build"