Showing posts with label #lists. Show all posts
Showing posts with label #lists. 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 )

Saturday, May 14, 2016

Why Tuples, when Python already has Lists ?

One of my student, very pertinently asked me, "Why do we need Tuples, when we already have a data structure called list ? Tuples are almost same like Lists, except that they are immutable. So, what's such a big deal about being immutable ?"

This question, inspired me to write this post and add some clarity on when to prefer "Tuples" over "Lists" in Python. I am assuming that the basic understanding of what a Tuple is and what a List is more or less understood by the reader, but is not able to decide which one to choose over the other. I intend to concentrate more on situations when it would make more [ programming ? ] sense to use "Tuples" rather than "Lists" to help answer the question.

Few distinctions between "Tuple" and "Lists" are :

  1. List is a data structure for storing and manipulating a collection of items. Tuple is not a data structure in the same sense, even though it helps to store a collection of items.
  2. Lists, by convention are used for storing collection of items that are of the same types [ homogeneous ]. Where as Tuples, by convention are used for storing collection of items that are of different types [ heterogeneous ]. Beware that this is only a coding style preference and the language as such does not support any such restriction.
  3. Individual items in a List can be modified and updated. Tuples are immutable, and thus its individual items cannot be modified or updated.
  4. The number of methods supported in a List are much more than those for a Tuple, since Lists allow us to manipulate its collection of items and thus need a lot more methods to support those manipulations.