# Python Tuples

A tuple is similar to a list. The difference is that we cannot change the elements of a tuple once assigned whereas we can change the elements of a list.

## Creating a Tuple in Python

The items/elements in a tuple are enclosed within parentheses ( ) and separated by commas.

a = ()


a is an empty tuple having no item.

mytuple = (10, 30, 20, 40)
print(mytuple)

(10, 30, 20, 40)

In the above example, mytuple is a tuple having three integers.

mytuple = (2, "Hello", [1, 2, 3], (100, 200), 2)
print(mytuple)

(2, 'Hello', [1, 2, 3], (100, 200), 2)

mytuple is a tuple having five items of different data types. Notice that the third item is a list having three items and the fourth item is another tuple having two items.

print(type(()))

<class 'tuple'>

Here type(()) is showing the type as tuple. Hence ( ) is a tuple as we already know.

A tuple can also be created without parentheses.

mytuple = 10, "Hello", 20
print(mytuple)
print(type(mytuple))

(10, 'Hello', 20)
<class 'tuple'>

In the above example, mytuple is a tuple having three elements.

### Creating a Tuple With One Item

To create a tuple with a single item, we need to add a comma after the item. If a comma is not added, then it is not considered a tuple.

var1 = ("Hello World",)
print(var1)
print(type(var1))

var2 = ("Hello World")
print(var2)
print(type(var2))

('Hello World',)
<class 'tuple'>
Hello World
<class 'str'>

We can see that var1 is a tuple whereas var2 is not a tuple (because comma is not added after the item). Look at another example.

var1 = (10,)
print(var1)
print(type(var1))

var2 = (10)
print(var2)
print(type(var2))

(10,)
<class 'tuple'>
10
<class 'int'>

Here var1 is a tuple whereas var2 is not a tuple.

## Accessing Elements from Tuple in Python

An element from a tuple can be accessed using its index.

Same as in lists and strings, every element in a tuple has a unique index based on its position. Indices start from 0. Therefore, the first element of a tuple has index 0, the second element has index 1, and so on.

To access any element of a tuple, we write name_of_tuple[index].

Therefore, the 2nd element of the tuple mytuple can be accessed by writing mytuple[1] (because the index of the 2nd element is 1).

mytuple = (4, 9, 6, 2)
print(mytuple[0])
print(mytuple[1])
print(mytuple[2])
print(mytuple[3])

4
9
6
2

### Negative Index in Python Tuple

We can also access an element of a tuple by using a negative index just like in lists and strings.

The last element of a tuple has index -1, second last element has index -2, and so on.

mytuple = (4, 9, 6, 2)

#accessing using indices
print(mytuple[0])
print(mytuple[1])
print(mytuple[2])
print(mytuple[3])

# accessing using negative indices
print(mytuple[-1])
print(mytuple[-2])
print(mytuple[-3])
print(mytuple[-4])

4
9
6
2
2
6
9
4

Here, mytuple[-1] returns the last element 2 of the list mytuple, mytuple[-2] returns the second last element 6, and so on.

Extracting elements from nested tuples and strings can be done in the same way as nested lists as shown in the following example.

mytuple = (4, [10, 20], (100, 200, 300), "Hello")

#accessing elements of nested list
print(mytuple[1][0])  # 10

#accessing elements of nested tuple
print(mytuple[2][1])  # 200

#accessing elements of nested string
print(mytuple[3][4])  # o

10
200
o

In this example, mytuple is a tuple which consists of four elements - an integer, a list, a tuple and a string. mytuple[1][0] prints the 1st element of the 2nd element of the tuple. Similarly, the other values are printed.

## Python Tuple Slicing

A range of elements from a tuple can be accessed using the slicing operator :.

To access elements from the ith index to the jth index of a tuple, we write name_of_tuple[i:j+1].

mytuple = (1,2,3,4,5)
print(mytuple[1:4])

[2, 3, 4]

mytuple = (1,2,3,4,5)

print(mytuple[1:4])

Output

[2, 3, 4]

mytuple = (1, 2, 3, 4, 5, 6)

# from 2nd element till 5th element
print(mytuple[1:5])

# from start till 5th element
print(mytuple[:5])

# from 5th element till end
print(mytuple[4:])

# from start till 3rd last element
print(mytuple[:-2])

# from 4th last element till 3rd last element
print(mytuple[-4:-2])

# from 3rd element till 3rd last element
print(mytuple[2:-2])

# all elements
print(mytuple[:])

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

We can also give a step to the slice to skip some number of elements while slicing.

Look at the following example.

mytuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# from 2nd element till 9th element
print(mytuple[1:9])

# from 2nd element till 9th element in step 2
print(mytuple[1:9:2])

# from 2nd element till 9th element in step 3
print(mytuple[1:9:3])

(2, 3, 4, 5, 6, 7, 8, 9)
(2, 4, 6, 8)
(2, 5, 8)

mytuple[1:9] returned the elements from the 1st index till the 8th index.

mytuple[1:9:2] also returned the elements from the 1st index till the 8th index, but it returned every 2nd element after the element having the start index. Therefore, 3, 5 and 7 got skipped.

mytuple[1:9:3] also returned the elements from the 1st index till the 8th index, but it returned every 3rd element after the element having the start index.

Giving a negative step returns the elements of a tuple in the reverse order. A step of -1 returns the reversed tuple.

mytuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# reversed tuple
print(mytuple[::-1])
# reversed tuple with step -2
print(mytuple[::-2])

(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
(10, 8, 6, 4, 2)

## Changing Elements of Python Tuple

Tuples are immutable, which means that their elements can’t be changed. Let’s try this:

mytuple = (1,2,"Hello World!")
mytuple[1] = 5

mytuple[1] = 5
TypeError: 'tuple' object does not support item assignment

This is the same error that we got while trying to change the elements of a string. Since tuple is also not mutable like a string, so we can't change the elements of a tuple.

## Deleting Python Tuple

We cannot delete any item from a tuple because tuples are immutable. Instead, we can delete an entire tuple using the del keyword.

mytuple = (1,2,"Hello World!")
del mytuple[1]

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

We tried to delete the 2nd element of a tuple and got an error.

mytuple = (1,2,"Hello World!")
del mytuple
print(mytuple)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mytuple' is not defined

We deleted the entire tuple mytuple. Thus, we got an error on printing the tuple after deleting it.

## Python Tuple Operations

### Tuple Concatenation (+)

Two or more tuples can be concatenated or combined using the + operator.

tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c', 'd')
tuple3 = tuple1 + tuple2
print(tuple3)

(1, 2, 3, 'a', 'b', 'c', 'd')

tuple1 and tuple2 are concatenated to form tuple3.

### Tuple Repetition (*)

A tuple can be repeated a specified number of times using the * operator.

tuple1 = (1, 2)
tuple2 = tuple1 * 3
print(tuple2)

(1, 2, 1, 2, 1, 2)

tuple1 is repeated 3 times to form tuple2.

### Python Tuple Membership Test

We can test if an element is present in a tuple using the membership operators in and not in.

mytuple = (1, 2, "Blue", "Green")
print(2 in mytuple)
print(4 in mytuple)
print("Green" not in mytuple)

True
False
False

### Python Iteration Through a Tuple

Like lists, we can iterate through a tuple also using a for loop.

colors = ("Blue", "Green", "Red")
for color in colors:
print(color)

Blue
Green
Red

A variable color goes to each element in the tuple colors and takes its value, and that value is printed on the screen.

## Different Ways to Create a Tuple in Pyhton

We already know how to create a tuple.

An empty tuple is created as follows.

mytuple = ()

A tuple having elements is created as follows.

mytuple = (1, 2, 3, 4)

It can also be created as follows.

mytuple = 1, 2, 3, 4

Tuples can also be created using the tuple() function. This function converts a sequence (range, list, string, tuple) or a collection(dictionary, set) into a tuple.

An empty tuple can be created using tuple() as shown below.

mytuple = tuple()
print(mytuple)

()

In the next example, a list and a string are converted to tuples.

tuple1 = tuple([1, 2, 3])  # list is converted to tuple
tuple2 = tuple("Codesdope")  # string is converted to tuple
print(tuple1)
print(tuple2)

(1, 2, 3)
('C', 'o', 'd', 'e', 's', 'd', 'o', 'p', 'e')

Note that all the characters of the string became the different elements of the tuple.

## Built-in Functions in Python for Tuples

The functions available in Python which can be used with tuples are shown below.

### len()

It returns the number of elements in a tuple.

mytuple = (1, 2, 3, 4, 5, 6)
print(len(mytuple))

6

### max()

It returns the element from a tuple that has the maximum value.

mytuple = (3, 2, 1, 5, 6, 4)
print(max(mytuple))

6

### min()

It returns the element from a tuple that has the minimum value

mytuple = (3, 2, 1, 5, 4)
print(min(mytuple))

1

### sum()

It returns the sum of all the elements in a tuple.

mytuple = (3, 2, 1, 5, 6, 4)
print(sum(mytuple))

21

### sorted()

It returns a sorted list from the tuple.

mytuple = (3, 2, 1, 5, 6, 4)
print(sorted(mytuple))

[1, 2, 3, 4, 5, 6]

To sort the elements in descending order, pass another argument reverse=True to the sorted() function.

mytuple = (3, 2, 1, 5, 6, 4)
print(sorted(mytuple, reverse=True))

[6, 5, 4, 3, 2, 1]

### any()

It returns True if any of the elements in a tuple are True. Otherwise, it returns False.

mytuple = (3, 2, 1, True)
print(any(mytuple))

True

any(mytuple) returned True because all the elements of the tuple are non-zero or True.

Look at another example where one element of the tuple is False.

mytuple = (3, 2, 1, False)
print(any(mytuple))

True

In the above example, one element of the tuple is False, but still the any() function returned True. This is because if at least one element is non-zero or True, then the function returns True.

### all()

It returns True if all the elements in a tuple are True. Otherwise, it returns False.

mytuple = (3, 2, 1, True)
print(all(mytuple))

True
mytuple = (3, 2, 1, False)
print(all(mytuple))

False

In this example, one element is False and so the all() function returned False.

## Other Tuple Functions

We can use the index() and count() functions which we use with lists with tuples as well.

languages = ('Python', 'C', 'Java', 'C++', 'Java')

print(languages.index('Java')) # printing index of first occurrence of 'Java'

print(languages.count('Java')) # printing count of 'Java'

2
2

In the above example, 'Java' is present at the indices 2 and 4 in the tuple languages. However, languages.index('Java') returned only the index 2 of its first occurrence.

print(languages.count('Java')) returned the number of times the element  'Java' is present in the tuple.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
You are only good as the chances you take.
- Al Pacino