Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between list and list[:] in python?

Tags:

python

What, if any, is the difference between list and list[:] in python?

like image 998
Jing Avatar asked Nov 02 '10 19:11

Jing


People also ask

What is [:] in Python list?

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.

Is list () Same as []?

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.

Is list () and [] the same in Python?

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.


2 Answers

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.

like image 107
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 12:10

Ignacio Vazquez-Abrams


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] 
like image 40
Matthew Mitchell Avatar answered Oct 02 '22 14:10

Matthew Mitchell