ds007
ds007

Reputation: 35

After switching brackets [] to list, would this be considered to be the same?

I commented out the list containing the odd numbers and added my_odds = list(range(1, 60, 2)) print(my_odds). I was wondering whats the difference between the list and the []? are they technically the same?

def first_code_from_headfirst():

   # odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55,
     #       57, 59]

    my_odds = list(range(1, 60, 2))
    print(my_odds)

    for el in range(5):
        right_this_minute = datetime.today().minute

        if right_this_minute in my_odds:
            print("this minute seems a little odd")

        else:
            print('not an odd minute.')

Upvotes: 0

Views: 74

Answers (1)

Ecir Hana
Ecir Hana

Reputation: 11468

The difference between [] and list is that one is syntactic construct and the other is function call. Which means:

import dis

def func():
    a = []

dis.dis(func)

  1           0 BUILD_LIST               0
              3 STORE_FAST               0 (a)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE  

whereas:

def func():
    a = list()

dis.dis(func)

  1           0 LOAD_GLOBAL              0 (list)
              3 CALL_FUNCTION            0
              6 STORE_FAST               0 (a)
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE 

So the former should be tiny bit faster as it does not have to search for the global name list. (This is for CPython 2.7.10)

Upvotes: 1

Related Questions