Python Tuples

  • Tuples are similar to lists, in that, they can contain an ordered sequence of objects
  • However, tuples are immutable. Which means, once created, you cannot add or remove items from a tuple.

Creating an empty tuple

An empty tuple can be created by just an empty pair of parens: ()


In [1]:
empty_tuple = ()
print empty_tuple


()

You cannot add item to the tuple


In [2]:
empty_tuple.append(1)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-8efa2d612532> in <module>()
----> 1 empty_tuple.append(1)

AttributeError: 'tuple' object has no attribute 'append'

In [3]:
dir(tuple)


Out[3]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']

Creating tuple with values


In [5]:
tuple1 = (1, 2, 4)
print tuple1


(1, 2, 4)

Reading values from Tuples

Reading values from tuples is similar to that of lists


In [6]:
print tuple1[0]


1

In [7]:
print tuple1[-1]


4

Length of tuple


In [8]:
print len(empty_tuple)
print len(tuple1)


0
3

Exercise

Find out advantages of tuples over lists and when to use which?


In [ ]: