sentence = "Hello"
print sentence
print sentence[:]
Both outputs the same thing, i.e. Hello
So, when and why to use/not use [:]
?
Thanks! :)
sentence = "Hello"
print sentence
print sentence[:]
Both outputs the same thing, i.e. Hello
So, when and why to use/not use [:]
?
Thanks! :)
As Nobi pointed out in the comments, there's already a question regarding Python's slicing notation. As stated in the answer to that question, the slicing without start and end values ([:]
) basically creates a copy of the original sequence.
However, you have hit a special case with strings. Since strings are immutable, it makes no sense to create a copy of a string. Since you won't be able to modify any instance of the string, there's no need to have more than one in memory. So, basically, with s[:]
(being s
a string) you're not creating a copy of the string; that statement is returning the very same string referenced by s
. An easy way to see this is by using the id()
(object identity) function:
>>> l1 = [1, 2, 3]
>>> l2 = l1[:]
>>> id(l1)
3075103852L
>>> id(l2)
3072580172L
Identities are different. However, with strings:
>>> s1 = "Hello"
>>> s2 = s1[:]
>>> id(s1)
3072585984L
>>> id(s2)
3072585984L
Identity is the same, meaning both are the same exact object.
Thee reason why you are getting Hello as output, is you are not passing any parameter.
L[start:stop:step]
Here L is your variable, which holds Hello. and start means the initial position of the string and stop means where you want to end your string with & step means how many char you want to skip.
For more information on this topic, visit this
See, if that resolved your issue.
>>> a = [1, 2, 3]
>>> b=a[:]
>>> id(b)
4387312200
>>> id(a)
4387379464
When you want to make a deep copy of an array.
>>> a='123'
>>> b=a[:]
>>> id(a)
4387372528
>>> id(b)
4387372528
But since string is immutable, string[:] has no difference with string itself.
P.S. I see most of people answering this question didn't understand what is the question at all.
a = [[]]
; b = a[:]; a[0] is b[0]` gives True. To do a true deep copy, use copy.deepcopy
](docs.python.org/3.4/library/copy.html#copy.deepcopy).
– lvc
Feb 9 '15 at 7:22
a = []; b = []; a is b
is False. And conversely, you can put whatever you want into the inner list and get the same result - mylist[:]
does not make copies of any of the objects in the list. Try a = [['a', 'b', 'c', 'd']]; b = a[:]; print(a[0] is b[0]); a[0].append('e'); print(b[0])
.
– lvc
Feb 9 '15 at 7:37