5

Is there any difference between list() and [] while initializing a list in Python 3?

Voiceroy
  • 330
  • 4
  • 14
  • To my knowledge they are equivalent. – Ottotos Jun 02 '20 at 14:24
  • 3
    Technically speaking, one is a function that returns an object casted to a list, and the other is the literal list object itself. Kinda like `int(0)` vs `0`. In practical terms there's no difference. – jfaccioni Jun 02 '20 at 14:25
  • 4
    I'd expect `[]` to be faster, because it does not involve a global lookup followed by a function call. Other than that, it's the same. – bereal Jun 02 '20 at 14:27
  • 1
    Compare `list = int; list()` with `list = int; []`. – chepner Jun 02 '20 at 15:11

5 Answers5

7

Since list() is a function that returns a list object and [] is the list object itself, the second form is faster since it doesn't involve the function call:

> python3 -m timeit 'list()'
10000000 loops, best of 3: 0.0853 usec per loop

> python3 -m timeit '[]'
10000000 loops, best of 3: 0.0219 usec per loop

So if you really want to find a difference, there's that. In practical terms they're the same, however.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25
4

they are close to equivalent; the constructor variant does a function lookup and a function call; the literal does not - disassembling the python bytecode shows:

from dis import dis


def list_constructor():
    return list()

def list_literal():
    return []


print("constructor:")
dis(list_constructor)

print()

print("literal:")
dis(list_literal)

this outputs:

constructor:
  5           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

literal:
  8           0 BUILD_LIST               0
              2 RETURN_VALUE

as for the timing: the benchmark given in this answer may be misleading for some (probably rare) cases. compare e.g. with this:

$ python3 -m timeit 'list(range(7))'
1000000 loops, best of 5: 224 nsec per loop
$ python3 -m timeit '[i for i in range(7)]'
1000000 loops, best of 5: 352 nsec per loop

it seems that constructing a list from a generator is faster using list than a list-comprehension. i assume this is because the for loop in the list-comprehension is a python loop whereas the same loop is run in the C implementation in the python interpreter in the list version.


also note that list can be reassigned to something else (e.g. list = int now list() will just return the integer 0) - but you can not tinker with [].

and while it may be obvious... for completeness: the two versions have a different interface: list accepts exactls on iterable as argument. it will iterate over it and put the elements into the new list; the literal version does not (except for explicit list-comprehensions):

print([0, 1, 2])  # [0, 1, 2]
# print(list(0, 1,2))  # TypeError: list expected at most 1 argument, got 3

tpl = (0, 1, 2)
print([tpl])           # [(0, 1, 2)]
print(list(tpl))       # [0, 1, 2]

print([range(3)])      # [range(0, 3)]
print(list(range(3)))  # [0, 1, 2]

# list-comprehension
print([i for i in range(3)])      # [0, 1, 2]
print(list(i for i in range(3)))  # [0, 1, 2]  simpler: list(range(3))
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
2

Functionally they produce the same result, different internal Python implementation:

import dis


def brackets():
    return []


def list_builtin():
    return list()
print(dis.dis(brackets))
  5           0 BUILD_LIST               0
              2 RETURN_VALUE
print(dis.dis(list_builtin))
 9           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE
Terry Spotts
  • 3,527
  • 1
  • 8
  • 21
1

Let us take this example:

A = ("a","b","c")
B = list(A)
C = [A]

print("B=",B)
print("C=",C)

# list is mutable:
B.append("d")
C.append("d")

## New result
print("B=",B)
print("C=",C)

Result:
B= ['a', 'b', 'c']
C= [('a', 'b', 'c')]

B= ['a', 'b', 'c', 'd']
C= [('a', 'b', 'c'), 'd']

Based on this example, we can say that: [ ] doesn't try to convert tuple into a list of elements while list() is a method that try to convert tuple into list of elements.

ivan .B
  • 96
  • 2
  • 4
0

The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.

sample_touple = ('a', 'C', 'J', 13)
list1 = list(sample_touple)
print ("List values ", list1)

string_value="sampletest"
list2 = list(string_value)
print ("List string values : ", list2)

Output :

List values  ['a', 'C', 'J', 13]                                                                                                                              
List string values :  ['s', 'a', 'm', 'p', 'l', 'e', 't', 'e', 's', 't']   

Where [] to direct declare as list

sample = [1,2,3]

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53