0
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?

  • 2
    All of them is almost same, but the last two are a little bit faster cus they are not using list compression. – Mehrdad Pedramfar Mar 11 '20 at 07:32
  • I think it depends on situation. If you are wondering about performance, you can do it yourself with `timeit`. – Boseong Choi Mar 11 '20 at 07:33
  • Does this answer your question? [What causes \[\*a\] to overallocate?](https://stackoverflow.com/questions/60549865/what-causes-a-to-overallocate) – a_guest Mar 11 '20 at 07:36

2 Answers2

3

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 desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

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.

Advantages of a range

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.

Advantages of a list

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.

Ivo Merchiers
  • 1,589
  • 13
  • 29