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