Difference between list() and [ ] in Python 3

Question:

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

Asked By: Voiceroy

||

Answers:

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]

Answered By: Avinash Dalvi

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
Answered By: Terry Spotts

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))
Answered By: hiro protagonist

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.

Answered By: jfaccioni

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.

Answered By: ivan .B
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.