Python : Tuples


Tuples are similar to lists but are immutable. Syntactically tuples differ lists by enclosing a sequence of objects within parentheses instead of square brackets.

>>> T = (1,3,'hello')
>>> type(T)
<type 'tuple'>

Like lists, tuples contain positionally ordered items and the position of items are zero-based, meaning the first item is indexed at 0, second item at 1, and so on. Slicing works just as in lists.

>>> T
(1, 3, 'hello')

>>> T[0]
>>> T[-1]

>>> T[:-1]
(1, 3)

Unlike lists, the items in the tuple can’t be modified in-place (immutable).

>>> T[0]=2
... error text ...
TypeError: 'tuple' object does not support item assignment

Unlike lists, tuples don’t support the methods append,extend, remove, and pop.

>>> T
(1, 3, 'hello')

>>> T.append(3)
... error text ...
AttributeError: 'tuple' object has no attribute 'append'

>>> T.remove(1)
... error text ...
AttributeError: 'tuple' object has no attribute 'remove'

>>> T.pop(3)
... error text ...
AttributeError: 'tuple' object has no attribute 'pop'

>>> T2 = (4,5,6)
>>> T.extend(T2)
... error text ...
AttributeError: 'tuple' object has no attribute 'extend'

Like lists, concatenation works in tuples. Note that concatenation of lists returns a list while concatenation of tuples returns a tuple.

>>> T + T2
(1, 3, 'hello', 4, 5, 6)

>>> L + L2
[1, 2, 3, 'hello', 'world']

Like lists, tuples do support the methods index and count.

>>> T
(1, 3, 'hello')  

>>> T.index(3) # the index of 3
>>> T.count(1) # how many 1s in T

The in operator works with tuple to test whether it has the item specified.

>>> T
(1, 3, 'hello')
>>> 1 in T

Tuples are faster than lists. If you’re defining a constant set of values and all you do is to iterate through the sequence, then prefer tuple instead of list.

>>> for t in T:
	print t


Tuples are used in string formatting.

>>> s = '*****'
>>> print( '%s python %s' % (s,s) )
***** python *****

>>> print( '{0} python {1}'.format(s,s) )
***** python *****

Since tuples are immutable, they can be used as dictionary keys.

>>> D = {(1,2):'hello'}
>>> D[(1,2)]

Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.

>>> list(T)
[1, 3, 'hello']

>>> tuple(L)
(1, 2, 3)

About Deepak Devanand

Seeker of knowledge
This entry was posted in Python and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s