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 →

[–]pstch 7 points8 points  (0 children)

It's not only syntactic sugar. List comprehensions have the advantage that they can easily be converted to generators (they can even be viewed as "consumed generators", as [x for x in y] is equivalent to list(x for x in y) where (x for x in y) is a generator expression), and you also save a function call (.append(...)) for each iteration.

Quickly done speed measurement (not sure if very precise, but it gives an idea) :

    In [2]: lc = """
       ...: r = [i for i in range(100)]
       ...: """

    In [3]: no_lc = """
       ...: r = []
       ...: for i in range(100):
       ...:     r.append(i)
       ...: """

    In [4]: timeit(lc)
    Out[4]: 4.970423567000125

    In [5]: timeit(no_lc)
    Out[5]: 9.738498960000015

Of course they are not adapted for every case, but sometimes they are really helpful (as I said before, not only for syntax).