# Tuple

A tuple in sequence of elements it is similar to a list, but tuple is immutable whereas the list is mutable. The  once it is created you can change the elements of a list.

How to create a tuple?

A tuple is created by placing  elements  inside square brackets () these elements is separated by commas.  Here the  parentheses are optional, however, it is a recommend to use them.

_tuple = (-1, 0, 1, 2)

print(_tuple)

_tuple = ("Hi", 1.0, 3.14159, 2+ 3j)

print(_tuple)

​​​​​​​_tuple = (1, (1,2,3), [10, 20, 30])

print(_tuple)

#Create a empty tuple

_tuple = ()

print(_tuple)

Output

`(-1, 0, 1, 2)`
`('Hi', 1.0, 3.14159, (2+3j))`
`(1, (1, 2, 3), [10, 20, 30])`
`()`

## What is tuple packing?

A tuple is created without using parentheses, it is known as a tuple packing.

_tuple = 1,2,3,4,5

print(_tuple)

Output

`( 1, 2, 3, 4, 5)`

## What is tuple unpacking?

A tuple can be unpacked, this means that each element of the tuple is assigned to an individual variable.

a,b,c,d,e = (1,2,3,4,5)

print( a , b, c, d, e)

Output

`( 1, 2, 3, 4, 5)`

Creating a tuple with one element is a bit tricky.

Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.

``my_tuple = (`"hello"`)``
`print`(type(my_tuple))  `# <class 'str'>`
`# Creating a tuple having one element`
``my_tuple = (`"hello"`,)``
`print`(type(my_tuple))  `# <class 'tuple'>`
`# Parentheses is optional`
``my_tuple = `"hello"`,``
`print`(type(my_tuple))  `# <class 'tuple'>`

Output

`<class 'str'>`
`<class 'tuple'>`
`<class 'tuple'>`

## How to access Tuple element(s)

There are the multiple  ways to the access the tuple elements, these are

Indexing

Negative indexing

Slicing

1. Indexing

Example:1

_tuple = ('P', 'y', 't', 'h', 'o', 'n')

print(_tuple[0])

print(_tuple[5])

print(_tuple[10])

print(_tuple ['a'])

Output

`P`
`n`
`IndexError: tuple index out of range`
`TypeError: tuple indices must be integers or slices, not str`

Example:2

_tuple = ('P', 'y', 't', 'h', 'o', 'n', ('c++','java','c'))

Output

`java`

### Note:

The  index operator `[]` used to access an element from a tuple. The  index starts from 0.

Try to access an index outside of the tuple index range will raise an Out of index error

The index must be an integer, otherwise it will raise the Type Error.

The nested elements  are accessed using nested indexing.

### 2. Negative Indexing

Python allows negative indexing to access its element as shown in the below diagram

 Index 0 1 2 3 4 5 'P' 'y' 't' 'h' 'o' 'n' Negative Index -6 -5 -4 -3 -2 -1

The index of the last element is -1

_tuple = ('P', 'y', 't', 'h', 'o', 'n')

print(_tuple[-1])

print(_tuple[-6])

Output

`n`
`p`

### 3. Slicing

Slicing allows to access the range of elements

 0 1 2 3 4 5 6 7 8 9 'd' 'i' 'c' 't' 'i' 'o' 'n' ' a 'r' 'y' -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

_tuple = ('d','i','c','t','i','o','n','a','r','y')

# elements 2nd to 4th

print(_tuple[1:5])

# elements beginning to 3rd element

print(_tuple[:-7])

# elements from 8th to end

print(_tuple[7:])

# elements from beginning to end

print(_tuple[:])

Output

` ('i', 'c', 't', 'i')`
`('d', 'i', 'c')`
`('a', 'r', 'y')`
`('d', 'i', 'c', 't', 'i', 'o', 'n', 'a', 'r', 'y')`

## Modify  an element in a tuple

Tuples are immutable once a tuple is created you cannot modifiy its element, trying to do so result in Error.   If a tuple contains  case of nested tuple the mutable data type like list, can be changed for example

# Changing tuple values Error

_tuple = (-1, 0, 1, 2, [3,4])

_tuple[3] =  4

# A mutable element can be changed

_tuple[4][0] = 5

print(_tuple)

Output

`TypeError: 'tuple' object does not support item assignment`
`(-1, 0, 1, 2, [5, 4])`

## Deleting an element of a tuple

Tuples are immutable you cannot delete the elements in a tuple, trying to do so results in an error.

_tuple = ('d','i','c','t','i','o','n','a','r','y')

del _tuple[0]

Output

`TypeError: 'tuple' object doesn't support item deletion`

Deleting a tuple

del statement is used to delete the entire tuple for example

_tuple = ('d','i','c','t','i','o','n','a','r','y')

del _tuple

print(_tuple)

Output

`NameError: name '_tuple' is not defined`

Concatenate tuples

The   +  operator is used to join the two tuples. This is called concatenation. For example

print(('a', 'b', 'c') + ('d', 'e', 'f'))

Output

` ('a', 'b', 'c','d', 'e', 'f')`

The  * operator  repeat the elements in a tuple for a given number of times for example

print(('a', 'b', 'c')  * 3)

Output

` ('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')`

Note:  Tuples are immutable  applying + and  *  operators on tuple  returns  a new tuple.

## Tuple Membership Test

The in and not in operators are used to check the existence of the element in a tuple for example

_tuple = ('P', 'y', 't', 'h', 'o','n')

# Check existence with in operator

print('P' in _tuple)

print('y' in _tuple)

print('p' not in _tuple)

print('a' not in _tuple)

Output

`True`
`True`
`True`
`True`

Iterating  a Tuple

The for loop allows to iterate tuple for example

names = ('Naryan', 'Nirmal', 'Girdhar', 'Sivaji')

for name in names:

print("Hello ", name)

Output

`Hello  Naryan`
`Hello  Nirmal`
`Hello  Girdhar`
`Hello  Sivaji`

We can use the while  loop allows to iterate tuple for example

counter = 0

names = ('Naryan', 'Nirmal', 'Girdhar', 'Sivaji')

length = len(names)

while(counter< length):

print("Hello", names[counter])

counter+=1

Output

`Hello  Naryan`
`Hello  Nirmal`
`Hello  Girdhar`
`Hello  Sivaji`

Tuple Methods

Tuple has  two methods these  are  count and index, examples of Python tuple are

_tuple = ('J', 'a', 'v', 'a')

​​​​​​​#count the occurrence of an element

print(_tuple.count('a'))

#returns the index of an element ,otherwise returns ValueError

print(_tuple.index('v'))

print(_tuple.index('x'))

Output

`2`
`3`
`ValueError: tuple.index(x): x not in tuple`

How list and tuple are similar?

List and tuple is a sequence type

Both list and tuple can store heterogeneous data types

How list and tuple are different?

List is mutable whereas, tuple is immutable

### ​​​​​​​Advantages of Tuple over List

The tuples are immutable  hence  iterating through a tuple is faster compared to the list.

Tuples can be used as key in the dictionary not a list

If you want to  pass  arguments in a function as write protected a tuple can be used.