Skip to content Skip to sidebar Skip to footer

When And Why To Use [:] In Python

sentence = 'Hello' print sentence print sentence[:] Both outputs the same thing, i.e. Hello So, when and why to use/not use [:] ? Thanks! :)

Solution 1:

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.


Solution 2:

>>> 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.


Solution 3:

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.


Post a Comment for "When And Why To Use [:] In Python"