Python : comprehension list, square brackets vs list()

498 views Asked by At

Hello I could not found the difference between using square brackets for comprehension list versus using list()

Is there a performance/ memory allocation difference ?

( same question for set and dict )

input = [1, 2, 3, 4]

B = [a * 2 for a in input if a > 1]

C = list(a * 2 for a in input if a > 1)

B_set = {str(a) for a in input if a > 1}

C_set = set(str(a) for a in input if a > 1)

B_dict = {str(a):a for a in input if a > 1}

C_dict = dict(str(a):b for a,b in input if a > 1) # NOT LEGAL

Thank you for your help

3

There are 3 answers

0
Xxxo On BEST ANSWER

We can check with the -mtimeit.

$ python -mtimeit "B = [a * 2 for a in list(range(1000)) if a > 1]"
5000 loops, best of 5: 86.7 usec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(1000)) if a > 1)"
2000 loops, best of 5: 110 usec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(1000)) if a > 1)"
2000 loops, best of 5: 110 usec per loop
$ python -mtimeit "B = {str(a): a for a in list(range(1000)) if a > 1}"
1000 loops, best of 5: 273 usec per loop
$ python -mtimeit "B = set(str(a) for a in list(range(1000)) if a > 1)"
1000 loops, best of 5: 287 usec per loop

So, as you can see, there is no considerable difference.

With bigger list, we have:

$ python -mtimeit "B = [a * 2 for a in list(range(100000)) if a > 1]"
20 loops, best of 5: 11.1 msec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(100000)) if a > 1)"
20 loops, best of 5: 14.2 msec per loop

Where we see a 3 msec difference, better for the [] case.

With even bigger number list, we have

$ python -mtimeit "B = [a * 2 for a in list(range(10000000)) if a > 1]"
1 loop, best of 5: 1.21 sec per loop
$ python -mtimeit "B = list(a * 2 for a in list(range(10000000)) if a > 1)"
1 loop, best of 5: 1.49 sec per loop

where we see a 0.28 sec difference, again [] is faster.

1
Ashish Karn On

[] is much faster than list() because [] is literal means python direct compile and create bytecode whereas list() is object which need name resolution, stack allocation, etc. before creating bytecode.

0
Andrej Kesely On

You can measure the speed with timeit module.

For example:

from timeit import timeit

lst = [1, 2, 3, 4] * 100

def fn1():
    return [a * 2 for a in lst if a > 1]

def fn2():
    return list(a * 2 for a in lst if a > 1)

t1 = timeit(lambda: fn1(), number=10_000)
t2 = timeit(lambda: fn2(), number=10_000)

print(t1)
print(t2)

Prints (AMD 2400G, Python 3.8):

0.2406109299918171
0.2905043710197788

So list comprehension is faster.