1

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?

2
  • 4
    Because x only needs to create a 1 while y creates a list and a 1... Commented Apr 20, 2017 at 0:16
  • A "real life" version of this question would be: why takes constructing and packaging an item more time than just constructing it. Commented Apr 20, 2017 at 1:37

1 Answer 1

2
  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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.