Tuple is similar to List in python language, both are sequential, index based data structure.

The main difference between tuples and list is that tuples are immutable i.e. we cannot modify a tuple’s content but List is mutable data structure. Also, tuples uses parenthesis and list uses square brackets.

This article will discuss about following in Tuples:

- Create an Empty Tuple
- Create Tuple with Homogeneous Elements
- Create Tuple with Heterogeneous Elements
- Create Tuple with Single Element
- Modify Elements of Tuple
- Accessing Elements of Tuple – From the Front
- Accessing Elements of Tuple – From the Back
- Search Within a Tuple
- Add Elements to a Tuple
- Delete an Element from a Tuple
- Iterate Over a Tuple
- Concatenation of Tuples
- Identify Length of a Tuple
- Slice a Tuple
- Count the Number of Elements in a Tuple
- Identify the Index of an Element in a Tuple
- All Tuple Examples in one Example tuples.py Program

### 1. Create an Empty Tuple

Tuple can be created by simply writing elements of tuple, separated by comma “,” enclosed by parenthesis. Parenthesis is optional, but it is good practice to enclose the elements with it.

The following creates an empty tuple.

>>> emptyTuple=(); >>> emptyTuple ()

You can also create an empty tuple with constructor as shown below

>>> empty=tuple(); >>> empty ()

Empty tuple can be useful in few algorithmic codes where empty structure is required in some cases.

### 2. Create Tuple with Homogeneous Elements

The following tuple has all integer values for it’s elements.

>>> intTuple=(1,2,3,5,6); >>> intTuple (1, 2, 3, 5, 6)

The following tuple has all string values for it’s elements.

>>> stringTuple=("geek1","geek2","geek3"); >>> stringTuple ('geek1', 'geek2', 'geek3')

### 3. Create Tuple with Heterogeneous Elements

The following tuple has a combination of both integers and strings for it’s elements.

>>> mixTuple=(1,2,3,4,"geek1","geek2","geek3"); >>> mixTuple (1, 2, 3, 4, 'geek1', 'geek2', 'geek3')

### 4. Create Tuple with Single Element

You can also create a tuple just with one element. But, make sure you use a comma as shown below. Without comma, you are not creating a single element tuple.

>>> t=(1,); >>> t (1,) >>> t1=(2); >>> t1 2

Note: Without extra comma, t1 will be integer variable instead of tuple. So to create a tuple with single element always use comma after the element.

### 5. Modify Elements of Tuple

Tuples are immutable, we cannot change the tuple once it is initialized, and that is why they are best keys for dictionaries

>>> primes=(3,5,7,11,13,17) >>> primes (3, 5, 7, 11, 13, 17) >>> primes[0] 3 >>> primes[0]=19 Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> primes[0]=19 TypeError: 'tuple' object does not support item assignment >>> It will throw an error whenever code try to modify its elements.

### 6. Accessing Elements of Tuple – From the Front

Tuple is an indexed data structure like array, in similar fashion we can access the elements of tuple using [] operator, index starts from ‘0’. And it will throw an error if code try to access tuple beyond its range

Element : 3 5 7 11 13 19 Index : 0 1 2 3 4 5

Accessing from front:

>>> primes=(3,5,7,11,13,19) >>> primes (3, 5, 7, 11, 13, 19) >>> primes[1] 5 >>> primes[6] Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> primes[6] IndexError: tuple index out of range

### 7. Accessing Elements of Tuple – From the Back

Accessing from end: Using negative indexing, ‘-1’ will point to last item and so on

Element: 3 5 7 11 13 17 Index : -6 -5 -4 -3 -2 -1

>>> primes=(3,5,7,11,13,17); >>> primes[-1] 17 >>> primes[-2] 13

### 8. Search Within a Tuple

An element can be searched in tuple using tuple’s membership test, ‘in’ keyword

>>> primes=(3,5,7,11,13,17); >>> primes (3, 5, 7, 11, 13, 17) >>> print (3 in primes) True >>> print (41 in primes) False

### 9. Add Elements to a Tuple

As already discussed Tuples are immutable so we cannot modify elements of a tuple, and addition of elements not supported, so append, add functions are not defined for tuple.

>>> primes (3, 5, 7, 11, 13, 17) >>> primes.append(91) Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> primes.append(91) AttributeError: 'tuple' object has no attribute 'append'

### 10. Delete an Element from a Tuple

We cannot modify elements of tuple, cannot delete it. But we can delete whole tuple along with its elements using ‘del’ keyword

>>> primes (3, 5, 7, 11, 13, 17) >>> del primes >>> primes Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> primes NameError: name 'primes' is not defined

### 11. Iterate Over a Tuple using For Loop

You can loop through items in a tuple using for loop as shown below.

>>> primes=(3,5,7,11,13,17); >>> primes (3, 5, 7, 11, 13, 17) >>> for prime in primes: print (prime); 3 5 7 11 13 17

For more details on for loop, refer to: 12 Essential Python For Loop Command Examples

### 12. Concatenation of Tuples

You can add (concatenate) to tuples using plus (+) as shown below.

>>> primes=(3,5,7,11,13); >>> primes (3, 5, 7, 11, 13) >>> names=("c","c++","java","angular"); >>> names ('c', 'c++', 'java', 'angular') >>> primes+names (3, 5, 7, 11, 13, 'c', 'c++', 'java', 'angular')

### 13. Identify Length of a Tuple

Use len function as shown below to identify the number of elements in a tuple.

>>> primes+names (3, 5, 7, 11, 13, 'c', 'c++', 'java', 'angular') >>> len(names+primes) 9

### 14. Slice a Tuple

‘:” can be used to get slice of a tuple, slice will start from first index and before the last index. And if one index is absent then all the items till that index.

Element : 3 5 7 11 13 Index : 0 1 2 3 4

>>> primes (3, 5, 7, 11, 13) >>> primes[0:3] (3, 5, 7) >>> primes[1:2] (5,) >>> primes[:3] (3, 5, 7) >>> primes[:-2] (3, 5, 7)

### 15. Count the Number of Elements in a Tuple

This function will return the no of elements in the tuple those are equal to the input parameter

>>> primes (3, 5, 7, 11, 13) >>> primes=(3,5,7,11,13,11,7); >>> primes.count(3) 1 >>> primes.count(11) 2 >>> primes.count(101) 0

### 16. Identify the Index of an Element in a Tuple

This function will return index of first element that is equal to input parameter

>>> primes (3, 5, 7, 11, 13, 11, 7) >>> primes.index(3) 0 >>> primes.index(11) 3 >>> primes.index(7) 2

If element doesn’t exist in tuple, it will throw an error

>>> primes.index(101) Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> primes.index(101) ValueError: tuple.index(x): x not in tuple

### 17. All Tuple Examples in one Sample Python Program

vi tuples.py

Copy/Paste the following to your tuples.py

# Creating an empty tuple emptyTuple=(); emptyTuple # Creating tuple with constructor empty=tuple(); empty # Creating tuple with homogeneous elements intTuple=(1,2,3,5,6); intTuple # Creating tuple with heterogeneous elements mixTuple=(1,2,3,4,"geek1","geek2","gee3"); mixTuple # Creating tuple with single element t=(1,); t # Modifying elements of Tuple primes=(3,5,7,11,13,17) # The following line will give an error message. #primes[0]=19 # Accessing tuple from front primes=(3,5,7,11,13,19) primes[1] # Accessing tuple from end primes[-1] # Search within Tuple primes=(3,5,7,11,13,17); print (3 in primes) print (43 in primes) # Adding elements to tuple # The following line will give an error message. #primes.append(91) # Deleting a Tuple del primes # Iterating over a tuple primes=(3,5,7,11,13,17); for prime in primes: print (prime); # Concatenation primes=(3,5,7,11,13); names=("c","c++","java","angular"); primes+names # Length of tuple len(names+primes) # Slicing operator primes[0:3] # Count function primes=(3,5,7,11,13,11,7); primes.count(3) # Index function primes.index(3)

{ 1 comment… add one }

Good article!