Previous | Next


Tuple is similar to list except that it doesn’t allow the sequence to change. That also mean, once data is assigned to a tuple, the data they hold cannot be changed under any circumstances. tuple is useful especially if your function is designed to return a set of constant list which doesn’t allow any modification. Example of tuples like mouse cursor coordinates, data mapping result, etc.

An empty tuple:

The empty tuple is written as two parentheses containing nothing.
>>> numbers = ()

To create a tuple:

Create tuple by separating the data with a comma.
>>> numbers = 0,1,1,2,3,3,3

To get length of a tuple:

Use len() to get the length of a tuple.
>>> len(numbers)
7

To counts the occurrences of an element in a tuple:

Use count() to return number of occurrences of value.
>>> count(1)
2
>>> count(2)
1
>>> count(3)
3

Access element in a tuple:

Use index to to get an element in a tuple.
>>> numbers[3]
2

To get a element in a tuple:

Use index to to get an element in a tuple.
>>> numbers[3]
2

To access ranges of elements in a tuple:

Use slice() to access more than one data item in a tuple.
>>> numbers[3:6] #accesses the items from index location 3 up-to-but-not-including index location 6.
(2, 3, 3)
>>> numbers[2:4] #accesses the items from index location 2 up-to-but-not-including index location 4.
(1, 2)
>>> numbers[0:3] #accesses the items from index location 0 up-to-but-not-including index location 3.
(0, 1, 1)
>>> numbers[:3] #accesses the items from index location 0 up-to-but-not-including index location 3.
(0, 1, 1)
>>> numbers[3:] #accesses the items from index location 3 up-to last index location.
(0, 1, 1)

Previous | Next