What's the difference between the following code:
foo = list()
And
foo = []
Python suggests that there is one way of doing things but at times there seems to be more than one.
One's a function call, and one's a literal:
>>> import dis
>>> def f1(): return list()
...
>>> def f2(): return []
...
>>> dis.dis(f1)
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>> dis.dis(f2)
1 0 BUILD_LIST 0
3 RETURN_VALUE
Use the second form. It's more Pythonic, and it's probably faster (since it doesn't involve loading and calling a separate funciton).
For the sake of completion, another thing to note is that list((a,b,c)) will return [a,b,c], whereas [(a,b,c)] will not unpack the tuple. This can be useful when you want to convert a tuple to a list. The reverse works too, tuple([a,b,c]) returns (a,b,c).
Edit: As orlp mentions, this works for any iterable, not just tuples.
dict()and{},tuple()and(), etc. - Casimir Crystal