Home > Enterprise >  Declaring a new list/set/dict in python
Declaring a new list/set/dict in python

Time:01-12

I was wondering if there was any difference (performance, speed, ...) between these two notations: new_list = [] and new_list = list() ?

Or is it a developer/team preference or even a recommendation in the language? What about sets and dictionaries?

CodePudding user response:

There are some differences like:

list(('x','y'))
#['x', 'y']

[('x','y')]
#[('x', 'y')]

list(set('x'))
#['x']

[set('x')]
#[{'x'}]

list() is a function call while [] is a literal.

Also, there is a module called dis dis doc:

The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.

To display the disassembly of lambda: list() and lambda: [] see below:

import dis
print(dis.dis(lambda: list()))
#output
 1           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

print(dis.dis(lambda: []))
#output
1           0 BUILD_LIST               0
              2 RETURN_VALUE

Also, list is a global name that can be overridden during runtime so it is highly discouraged to use list as your variable name. Coz you do not want to override in-built list.

  • Related