python - What does [:] do? -
return self.var[:]
what return?
python permits "slice" various container types; shorthand notation taking subcollection of ordered collection. instance, if have list
foo = [1,2,3,4,5]
and want second, third, , fourth elements, can do:
foo[1:4]
if omit 1 of numbers in slice, defaults start of list. instance
foo[1:] == [2,3,4,5] foo[:4] == [1,2,3,4]
naturally, if omit both numbers in slice entire list back! however, copy of list instead of original; in fact, standard notation copying list. note difference:
>>> = [1,2,3,4] >>> b = >>> b.append(5) >>> [1, 2, 3, 4, 5] >>> >>> = [1,2,3,4] >>> b = a[:] >>> b.append(5) >>> [1, 2, 3, 4]
this occurs because b = a
tells b
point same object a
, appending b
same appending a
. copying list a
avoids this. notice runs 1 level of indirection deep -- if a
contained list, say, , appended list in b
, still change a
.
by way, there optional third argument slice, step parameter -- lets move through list in jumps of greater 1. write range(100)[0::2] numbers 100.
Comments
Post a Comment