What, if any, is the difference between list
and list[:]
in python?
Individual elements in a list can be accessed using an index in square brackets. This is exactly analogous to accessing individual characters in a string. List indexing is zero-based as it is with strings. The [:] syntax works for lists.
When you convert a dict object to a list, it only takes the keys. However, if you surround it with square brackets, it keeps everything the same, it just makes it a list of dict s, with only one item in it.
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.
When reading, list
is a reference to the original list, and list[:]
shallow-copies the list.
When assigning, list
(re)binds the name and list[:]
slice-assigns, replacing what was previously in the list.
Also, don't use list
as a name since it shadows the built-in.
The latter is a reference to a copy of the list and not a reference to the list. So it's very useful.
>>> li = [1,2,3] >>> li2 = li >>> li3 = li[:] >>> li2[0] = 0 >>> li [0, 2, 3] >>> li3 [1, 2, 3]
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