semantics of [:]
Luis Zarrabeitia
kyrie at uh.cu
Fri Nov 20 12:45:11 EST 2009
On Friday 20 November 2009 11:15:55 am Esmail wrote:
> Could someone help confirm/clarify the semantics of the [:] operator
> in Python?
In short, a[:], when "a" is a list, returns a slice ("sublist") of "a" that
happens to contain all the elemnts of "a". In general, a[low:upper:step] will
give you the sublist containing all the items from low to upper, with the
specified step size. When you omit the three arguments, you get the whole
list.
When used on the left side, it means "replace the contents of this slice with
the contents of this iterable". (The get slice and set slice behaviors are
defined by the class of «a», so while this explanation applies to list, it
may not apply, and will likely not apply, to other data structures).
Note that the sublist is always another list (even when you get the full
slice). So, in your experiments:
> ############# 1 ##################
> b = a[:] # b receives a copy of a, but they are independent
Indeed, a[:] would return a full slice, i.e, another list containing the same
elements as «a»
> # The following two are equivalent
> ############# 2 ##################
> c = []
> c = a[:] # c receives a copy of a, but they are independent
> ############# 3 ##################
> d = []
> d[:] = a # d receives a copy of a, but they are independent
Not exactly, but the difference is not big in this particular circumstance.
In (2), you create an empty list, discard it immediately, create another list
a[:] with the contents of «a», and assign it to «c».
In (3) you create an empty list, and then fill it with the elements of «a».
To see the difference, try:
e = []
g = e
e = a[:]
print g
and
e = []
g = e
e[:] = a
print g
> ### 1 ### is the preferred, shorter way to do what ## 2 ## and ## 3 ##
> do.
Depends on what you want to achieve. Some times, you need to keep the list and
change the contents. That would be (3). For instance, when updating
the "dirnames" output of the iterator returned by os.walk . Some times, you
need to discard de old list, and get a new one. (1) would be the way to go.
Note that (2) and (1) are the same, in both you discard the old value, if it
exists, but in (2) you are creating a new list only to discard it right
away - you shouldn't do that.
> Am I correct with this?
I hope I could help.
--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
More information about the Python-list
mailing list