# Tuples¶

Tuple is an immutable collection of elements (may be of same or different types), which is indexed by a 0-based integer. A 2-tuple can represent a point in 2-D plane, or a 3-Tuple can represent a point in 3-D plane.

## Creating Tuples¶

• Creating an empty tuple
x = ()  # () denotes a tuple type
# or
x = tuple()

• Creating list with some initial elements
x = (2,3,0,'g')

In :

x = (2,3)

In :

x

Out:

(2, 3)

In :

x = (2,)  # x = (2) assigns int 2 to x. To make it a tuple, a comma is appended

In :

x

Out:

(2,)

In :

x + (1,2)

Out:

(2, 1, 2)


Tuples are immutable. So once a tuple is created, its contents are permanent unless it is reassigned with another tuple.

Tuples can also be Indexed and Sliced like lists

In :

x

Out:

(2,)

In :

x = x + (1,3,4)   # Reassignment

In :

x

Out:

(2, 1, 3, 4)

In :

x

Out:

1

In :

x[2:5]

Out:

(3, 4)

In :

x[::-1]

Out:

(4, 3, 1, 2)


## Operations on Tuples¶

Since tuples are immutable, operations do not modify the original tuple

Here are some of the operations on list. They are member functions of class tuple. If x is a tuple,

• x.index(ele) - searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use in to check without a ValueError).
• x.count(ele) - counts the number of occurances of ele in x

Membership operator in is also supported

In :

x

Out:

(2, 1, 3, 4)

In :

2 in x

Out:

True

In :

x.count(2)

Out:

1

In :

x.index(3)

Out:

2


Using a list of tuples, one can model a collection of points in space