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.
list is a global name that may be overridden during runtime. list() calls that name. [] is always a list literal.
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. I'd expect [] to be faster, because it does not involve a global lookup followed by a function call.
() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.
copy() will copy list1 into list2 . That's fine and everything, but it's longer to type than the second way and it just doesn't feel as clean. list2 = list1[:] will put all of the contents of list1 into list2 . This is less typing and most Python programmer's preferred way of copying a list.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With