Showing posts with label #learnings. Show all posts
Showing posts with label #learnings. Show all posts

Monday, July 17, 2017

The Curious Case of Python String Slicing

We were studying about Python strings and we tried to understand Python String Slicing through an example. We found a very strange [at least at first look] result when we tried to use String Slicing for creating a copy of the string.

To better understand the scenario and the result, lets start with the basics of integers and lists w.r.t to slicing.

>>> m = 10         # Integer m initialised to 10
>>> n = m           # Another integer n storing the same value as in m
>>> print m, n
10 10

>>> id(m), id(n)
( 140204825415168 , 140204825415168 ) # <-- Both are of the same id
A variable name in Python, is a "tag" name associated with a memory location.
In the above scenario, when we initialised variable m, Python associated a tag name m with memory location [ 140204825415168 ] ( For this discussion, assume that id represents memory location )