**Status: Completed**

A **Tuple** is a sequence of immutable elements, It is similar to a list but uses different syntax. With tuples, we cannot change elements. This makes programs more predictable. So tuples can be used as values, unlike classes, they never change.

**Define Tuple:**

A tuple is immutable: We cannot change after it was created. For this reason, the creation syntax is necessary. We use parentheses “(” and “. ” to create tuples. To create a tuple with no elements(empty tuple), use only the two parentheses “()”. For a tuple with one element, use a trailing comma. This comma helps Python tell that you don’t mean an expression, such as (5). For a tuple with two or more elements, use a comma between elements. No ending comma is needed.

Example:

>>> x = () # Empty Tuple >>> y = ('red',) # Tuple with one element >>> z = ('red', 'blue') # Tuple with two elements >>> type(x) <type 'tuple'> >>> print x () >>> print y ('red',) >>> print z ('red', 'blue')

**Note:** Any set of multiple elements, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc. Python interprets default to tuples, as shown in example below;

Example:

>>> T = 145, 165, 74, 908, 1001 >>> T (145, 165, 74, 908, 1001) >>> type(T) <type 'tuple'> >>> t = 'Asia', 'Africa', 'America' >>> t ('Asia', 'Africa', 'America') >>> type(t) <type 'tuple'>

**Accessing Tuple Elements:**

The syntax for accessing the elements of a tuple is the same as the syntax for accessing the list. The bracket operator ‘[]’ not to be confused with an empty list. The expression inside the brackets specifies the index. len(T) function returns the number of elements in the tuple, T[i] returns the element at index “i” (the first elements has index 0), and T[x:y] returns a new tuple, containing the elements between x and y.

Example:

>>> T = ("Bill", "Carlos", "Warren", "Amancio", "Larry", "Charles") >>> len(T) 6 >>> T[0] 'Bill' >>> T[1] 'Carlos' >>> T[2] 'Warren' >>> T[3] 'Amancio' >>> T[4] 'Larry' >>> T[5] 'Charles' >>> T[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range

In above example “T” is a tuple of items as a string, len(T) returns the number of elements in “T” i.e. 6. As we know the first element has index 0, T[0], T[1], T[2], T[3], T[4], T[5] returns the respective elements as tuple “T”. The tuple “T” is consists of 6 elements, but when you try to access the T[6] it will raise “IndexError”. This is because the list has only six elements and we are working to access 7th element.

We can access tuple using negative indices as shown in example below;

Example:

>>> T = ("Bill", "Carlos", "Warren", "Amancio", "Larry", "Charles") >>> T[-6] 'Bill' >>> T[-5] 'Carlos' >>> T[-4] 'Warren' >>> T[-3] 'Amancio' >>> T[-2] 'Larry' >>> T[-1] 'Charles'

**Tuple Slicing:**

We can get a subset of a tuple, called a “slice”, by specifying two indices (same as a list). The return value is a new tuple containing all the elements of the tuple, in order, starting with the first slice index, up to second slice index, but not including the second slice index. Slicing works if one or both of the slice indices is negative. Lists are zero-based, so T[0:4] returns the first four elements of the tuple, starting at T[0], up to but not including T[4].

Example:

>>> T = ("Bill", "Carlos", "Warren", "Amancio", "Larry", "Charles") >>> T[0:4] ('Bill', 'Carlos', 'Warren', 'Amancio') >>> T[0:5] ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry') >>> T[3:5] ('Amancio', 'Larry') >>> T[2:6] ('Warren', 'Amancio', 'Larry', 'Charles') >>> T[-4:-2] ('Warren', 'Amancio') >>> T[-6:-2] ('Bill', 'Carlos', 'Warren', 'Amancio')

As we have learned in python list left slice index is 0, you can leave it out. So T[:3] is the same as T[0:3].Similarly, if the right slice index is the length of the tuple, you can leave it out. So T[3:] is the same as T[3:6], because this tuple has six elements. In this six-element tuple, T[:3] returns the first three elements, and T[3:] returns the last three elements. In fact, T[:n] will always return the first n elements, and L[n:] will return the rest, regardless of the length of the tuple. If both slice indices are left out, all items in the tuple are included. But this is not the same as the original T tuple; it is a new tuple that happens to have all the same elements. T[:] is shorthand for making a complete copy of a tuple. As Shown in example below;

Example:

>>> T = ("Bill", "Carlos", "Warren", "Amancio", "Larry", "Charles") >>> T[:3] ('Bill', 'Carlos', 'Warren') >>> T[3:] ('Amancio', 'Larry', 'Charles') >>> T[:] ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles')

**Updating and Removing Elements from Tuple:**

As we know tuples are immutable; we cannot update or remove any elements from the tuple. We delete the whole tuple and create a new tuple with new elements. Once we try to update or remove any elements it will raise ‘TypeError’ as shown in example below;

Example:

>>> T = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> T ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> T[0] = 'Jack' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> T[4] = 'Jack' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment

>>> T = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> T ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> del T[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion >>> del T[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion

We can remove the whole tuple using the del method.

Example:

```
>>> T = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles')
>>> T
('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles')
>>> del T
>>> T
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'T' is not defined
```**Tuple Operators:**

As we know, we cannot change tuples once it is created, but tuples can be concatenated with the + operator. Tuple = tuple + other-tuple. The + operator returns a new (concatenated) tuple as a value. The * operator works on tuple as a repeater. T = [‘Red’, ‘Blue’] * 3 is equivalent to li = [‘Red’, ‘Blue’] + [‘Red’, ‘Blue’] + [‘Red’, ‘Blue’], which concatenates the three tuples into one, as shown in example below;

Example:

>>> T1 = ("Jim", "Jam") >>> T2 = ("Pim", "Pam") >>> T = T1 + T2 >>> T ('Jim', 'Jam', 'Pim', 'Pam') >>> T1 = ("Bill", "Carlos") >>> T2 = ("Warren", "Amancio") >>> T = T1 + T2 >>> T ('Bill', 'Carlos', 'Warren', 'Amancio') >>> T1 = ("Bill", "Carlos") >>> T2 = ("Warren", "Amancio") >>> T = T1 + T2 >>> T ('Bill', 'Carlos', 'Warren', 'Amancio')

Using ‘in’ operator we can check presence element is in the tuple, which returns boolean value i.e. True or False. As shown in the example below, ‘Red’ is one of the elements of tuple ‘T’ it returns ‘True, ‘ and Blue is not in tuple ‘T’ so it returns ‘False.’

Example:

>>> T = ('Red', 'Purple', 'Green', 'Yellow', 'Black') >>> 'Red' in T True >>> 'Black' in T True >>> 'Blue' in T False >>> 'Green' in T True

**Python Builtin Methods for Tuple:**

Python has many builtin methods for tuple which are described below with an example.

**cmp() :** The method cmp() compares elements of two tuples. If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers. If numbers, perform numeric coercion if necessary and compare. If either element is a number, then the other element is “larger” (numbers are “smallest”). If either element is a number, then the other element is “larger” (numbers are “smallest”). If we reached the end of one of the tuple, the longer tuple is “larger.” If we exhaust both tuples and share the same data, the result is a tie, meaning that 0 is returned.

Example:

>>> T = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> t = ('Red', 'Purple', 'Green', 'Yellow', 'Black', 'Blue') >>> cmp(T, t) -1 >>> T > t False >>> cmp(t, T) 1 >>> t > T True >>> T = (12, 56, 76, 32) >>> t = (55, 45, 34, 99) >>> cmp(T, t) -1 >>> T > t False >>> cmp(t, T) 1 >>> t > T True

**len() :** The method len() returns the number of elements in the tuple.

Example:

>>> T = (12, 56, 76, 32, 45) >>> len(T) 5 >>> t = (55, 45, 34) >>> len(t) 3

**max():** The method max returns the elements from the tuple with maximum value.

Example:

>>> T = (12, 56, 76, 32, 45) >>> max(T) 76 >>> t = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> max(t) 'Warren'

**min():** The method min() returns the elements from the tuple with a minimum value.

Example:

>>> T = (12, 56, 76, 32, 45) >>> min(T) 12 >>> t = ('Bill', 'Carlos', 'Warren', 'Amancio', 'Larry', 'Charles') >>> min(t) 'Amancio'

Tuples can be used in place of lists where the number of items is known and small, for example when returning multiple values from a function.

**So what are tuples good at?**

- Tuples are faster than lists. If you’re defining a fixed set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list.
- It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that special thought (and a specific function) is required to override that.

**Note:** 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.

## Recent Comments