Joesph
Joesph

Reputation: 71

Why do lists take more time to create in Python?

In Python, why is it that list take more time to create, than a plain variable?

Let's say you create 2 variables:

x = 1
y= [1]

Lets say you these variables millions of times and compare their time to run.

Since all variables in Python are created on the heap, why is that variable y, which is the list, take more time to create than x?

Upvotes: 1

Views: 87

Answers (1)

Prune
Prune

Reputation: 77847

  1. The constant 1 is pre-loaded as a "common" constant. There is no new object built in the x assignment, merely copying the reference of an existing object.
  2. A list is a mutable object, and requires class instantiation, including executing the constructor of an open-ended value that requires parsing -- minimal, but not insignificant.

Upvotes: 2

Related Questions