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
Bharath Pabba
  • 1,725
  • 5
  • 16
  • 24
  • 3
    Nothing? They both result in a list with one item (`4`). If you want to *time* them try the [timeit](https://docs.python.org/3/library/timeit.html) module. ... `t = Timer('node_to_visit=[4]')` and `t1 = Timer('node_to_visit=[];node_to_visit.append(4)')` – wwii Mar 09 '21 at 18:09
  • 1
    https://stackoverflow.com/questions/33044883/why-is-the-time-complexity-of-pythons-list-append-method-o1 – ddejohn Mar 09 '21 at 18:11
  • Check out [Which is faster to initialize lists](https://www.geeksforgeeks.org/python-which-is-faster-to-initialize-lists/) – DarrylG Mar 09 '21 at 18:35

2 Answers2

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
wwii
  • 23,232
  • 7
  • 37
  • 77
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.

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37