Tuples

Python's tuple data structure is immutable, meaning we cannot change the elements of the tuples. Basically, a tuple is a sequence of values that are separated by commas and are enclosed in parentheses ( ). Like lists, tuples are an ordered sequence of elements:

>>> t1 = 'h', 'e', 'l', 'l', 'o'

Tuples are enclosed in parentheses ( ):

>>> t1 = ('h', 'e', 'l', 'l', 'o')

You can also create a tuple with a single element. You just have to put a final comma in the tuple:

>>> t1 = 'h',
>>> type(t1)
<type 'tuple'>

A value in parentheses is not a tuple:

>>> t1 = ('a')
>>> type(t1)
<type 'str'>

We can create an empty tuple using the tuple() function:

>>> t1 = tuple()
>>> print (t1)
()

If the argument is a sequence (string, list, or tuple), the result is a tuple with the elements of the sequence:

>>> t = tuple('mumbai')
>>> print t
('m', 'u', 'm', 'b', 'a', 'i')

Tuples have values between parentheses ( ) separated by commas:

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

The slice operator selects a range of elements.

>>> print t[1:3]
('b', 'c')