0

What is the difference between these two approaches?

import time

start_time = time.time()
node_to_visit = [4]
print("My program took", time.time() - start_time, "to run")

start_time = time.time()
node_to_visit = []
node_to_visit.append(4)
print("My program took", time.time() - start_time, "to run")

Output:

My program took 7.43865966796875e-05 to run
My program took 0.00012230873107910156 to run
3
  • 3
    Nothing? They both result in a list with one item (4). If you want to time them try the timeit module. ... t = Timer('node_to_visit=[4]') and t1 = Timer('node_to_visit=[];node_to_visit.append(4)') Commented Mar 9, 2021 at 18:09
  • 1
    stackoverflow.com/questions/33044883/… Commented Mar 9, 2021 at 18:11
  • Check out Which is faster to initialize lists Commented Mar 9, 2021 at 18:35

2 Answers 2

2

What is the difference between these two approaches?

>>> import dis
>>> def f():
...     x = [4]
...
>>> def g():
...     x = []
...     x.append(4)
...

The first takes fewer bytecode operations than the second.

>>> dis.dis(f)
  2           0 LOAD_CONST               1 (4)
              2 BUILD_LIST               1
              4 STORE_FAST               0 (x)
              6 LOAD_CONST               0 (None)
              8 RETURN_VALUE
>>> dis.dis(g)
  2           0 BUILD_LIST               0
              2 STORE_FAST               0 (x)

  3           4 LOAD_FAST                0 (x)
              6 LOAD_METHOD              0 (append)
              8 LOAD_CONST               1 (4)
             10 CALL_METHOD              1
             12 POP_TOP
             14 LOAD_CONST               0 (None)
             16 RETURN_VALUE
>>>

>>> dis.dis(lambda : [4])
  1           0 LOAD_CONST               1 (4)
              2 BUILD_LIST               1
              4 RETURN_VALUE
>>> dis.dis(lambda : [].append(4))
  1           0 BUILD_LIST               0
              2 LOAD_METHOD              0 (append)
              4 LOAD_CONST               1 (4)
              6 CALL_METHOD              1
              8 RETURN_VALUE
Sign up to request clarification or add additional context in comments.

Comments

1

I think the most obvious answer to the difference in time would be that example 1 takes 1 step to create a list [4] while example 2 takes 2 steps to create the same list. Also, while I don't know how long it takes to initialize variables of different data types, I do know that variable initialization is (relatively) much shorter than function/method calls.

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.