n=[n for n in range(10)]
print(n)
r=list(range(10))
print(r)
a=range(0,10)
print(list(a))
Is there any handful advantages of these particular notations?
n=[n for n in range(10)]
print(n)
r=list(range(10))
print(r)
a=range(0,10)
print(list(a))
Is there any handful advantages of these particular notations?
Python has a timeit
module for quick benchmarks:
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("[n for n in range(10)]")
0.4846451000000229
>>> timeit.timeit("list(range(10))")
0.3175106840000126
>>>
Obviously, using list()
is faster. It's also less verbose and the intent is clearer IMHO (list comprehensions are usually used to transform/filter iterables).
Bruno already explained why list comprehensions might not be ideal, but I wanted to emphasize some difference between lists and ranges.
It's important to note that a list
and a range
have some different functionality and methods. So the answer to 'which one is better' depends on your application.
A range is an iterable and doesn't have to keep all numbers in memory. Python for example has no issue with range(int(1e20))
, but list(range(int(1e20)))
will throw an error.
A range can also be queried much more efficiently. Compare the following code snippet:
>>> from timeit import timeit
>>> timeit("100 in numbers",setup='numbers=range(10000)')
0.1061642
>>> timeit("100 in numbers",setup='numbers=list(range(10000))')
1.2257957
For this case, a range is 10x faster to query, and this will difference will only increase for larger lists.
The biggest difference is that a list can contain any type of objects. So if you want your numbers to be floats, then this is the easier solution.
Additionally, it allows you to append or delete single entries. So if you need some custom ordering of your numbers, then a list might be easier.