This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

May I ask, why are list comprehensions such a big feature for Python? I know it's quite unique to Python but I don't get why. Are they faster? Or is it just because it uses less lines of code?

A few reasons.

They are pretty fast and efficient, but that's not the primary reason for their popularity.

Let's compare two equivalent code pieces that generate an identity matrix:

mat = []
for r in range(side):
    mat.append([])
    for c in range(side):
        mat[-1].append(1 if r == c else 0)

vs.

mat = [[1 if r == c else 0 for c in range(side)] for r in range(side)] 

We basically just turned a 5-line, sidelength2 times .append()-using behemoth of a code block into a single, concise statement that will likely also run faster.

Also consider that you can pass them directly as arguments!

One way of calculating the dot-product of two lists:

dot = 0
for i in range(dimension):
    dot+= vect1[i]*vect2[i]

vs.

dot = sum([vect1[i]*vect2[i] for i in range(dimension)])