Python Tuple#

Learn everything about Python tuples. More specifically, what are tuples, how to create them, when to use them and various methods you should be familiar with.

What is Tuple in Python?#

A tuple in Python is similar to a list. Only the difference is that list is enclosed between square bracket [], tuple between parentheses () and we cannot change the elements of a tuple once it is assigned, i.e., immutable whereas we can change the elements of a list i.e., mutable.

Summary#

Data types

Type

String

immutable

List

mutable

Tuple

immutable

Creating Python Tuple#

A tuple is created by placing all the items (elements) inside parentheses (), separated by commas ,. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

# Example:

# Different types of tuples

# Empty tuple
my_tuple1 = ()
print(my_tuple1)  # ▶ ()

# Tuple having integers
my_tuple2 = (1, 2, 3)
print(my_tuple2)  # ▶ (1, 2, 3)

# tuple with mixed datatypes
my_tuple3 = (1, "Hello", 3.4)
print(my_tuple3)  # ▶ (1, "Hello", 3.4)

# nested tuple
my_tuple4 = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple4)  # ▶ ("mouse", [8, 4, 6], (1, 2, 3))
len(my_tuple4)    # ▶ 3
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
3

A tuple can also be created without using parentheses. This is known as tuple packing.

# Example:

my_tuple = 3, 4.6, "dog"   # ∵ paranthesis () is not mandatory
print(my_tuple)  # ▶ (3, 4.6, 'dog')

# tuple unpacking is also possible
a, b, c = my_tuple

print(a)        # ▶ 3
print(b)        # ▶ 4.6
print(c)        # ▶ dog
(3, 4.6, 'dog')
3
4.6
dog
# Example:

t1 = ('a b', 1, 2, 3.14, "HelloWorld")
t2 = "a", "b", "c", "d"

#tuple contain other list and tuple
t3 =(1, 2, 3, ['a','b','c'], ('z', 26))

print(t1)  # ▶ ('a b', 1, 2, 3.14, 'HelloWorld')
print(t2)  # ▶ ('a', 'b', 'c', 'd')
print(t3)  # ▶ (1, 2, 3, ['a', 'b', 'c'], ('z', 26))
('a b', 1, 2, 3.14, 'HelloWorld')
('a', 'b', 'c', 'd')
(1, 2, 3, ['a', 'b', 'c'], ('z', 26))

Creating a tuple with one element is a bit tricky.

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

# Example:

t1 = 5  # without () and comma ","
print(t1)       # ▶ 5  
print(type(t1)) # ▶ <class 'int'>

t2 = 5, # with ","
print(t2)       # ▶ (5,)
print(type(t2)) # ▶ <class 'tuple'>

t3 = (5) # without ","  That means () is not important, ',' is important
print(t3)       # ▶ 5
print(type(t3)) # ▶ <class 'int'>

t4 = (5,)       
print(t4)       # ▶ 5
print(type(t4)) # ▶ <class 'tuple'>
5
<class 'int'>
(5,)
<class 'tuple'>
5
<class 'int'>
(5,)
<class 'tuple'>

Access Tuple Elements#

There are various ways in which we can access the elements of a tuple.

1. Indexing#

We can use the index operator [] to access an item in a tuple, where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,… in this example) will raise an IndexError.

The index must be an integer, so we cannot use float or other types. This will result in TypeError.

# Accessing tuple elements using indexing

my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0])   # ▶ 'p' 
print(my_tuple[5])   # ▶ 't'

print("Last index:", len(my_tuple) - 1)             # ▶ Last index: 5
print("Last element:", my_tuple[len(my_tuple) - 1]) # ▶ Last element: t

# Index must be within range
# print(my_tuple[6]) # ▶ IndexError: list index out of range

# Index must be an integer
# my_tuple[2.0] # ▶ TypeError: tuple indices must be integers or slices, not float
p
t
Last index: 5
Last element: t
# Example: 

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[2][0])  # ▶ 1  ∵ element with index 2 and within sub-element with index 0
print(n_tuple[0][3])  # ▶ s  ∵ element with index 0 and within sub-element with index 3
1
s
# Example:

t=("helloworld",'xyz',1,-2,3.6)
for x in t:
    print(x)
helloworld
xyz
1
-2
3.6

2. Negative Indexing#

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

# Example: Negative indexing for accessing tuple elements

my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

print(my_tuple[-1])   # ▶ t
print(my_tuple[-6])   # ▶ p
t
p
# Example:

t=(3,7,4,2)

print(t[2])           # ▶ 4
print(t[1:3])         # ▶ (7, 4)
print(t[-3])          # ▶ 7
print(t[-4:-2])       # ▶ (3, 7)
print(t[-1 :  : -1])  # ▶ (2, 4, 7, 3) ∵ start from -1 and step =-1 so its basicly return reverse tuple
4
(7, 4)
7
(3, 7)
(2, 4, 7, 3)

3. Slicing#

We can access a range of items in a tuple by using the slicing operator :(colon).

Syntax:

tuple[start : stop : step]

by default step is +1

# Example: Accessing tuple elements using slicing

my_tuple = ('p','r','o','g','r','a','m','i','n','g')

# elements 2nd to 4th
print(my_tuple[1:4])   # ▶ ('r', 'o', 'g')

# elements beginning to 2nd
print(my_tuple[:-7])   # ▶ ('p', 'r')

# elements 8th to end
print(my_tuple[7:])    # ▶ ('i', 'z')

# elements beginning to end
print(my_tuple[:])     # ▶ ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n','g')
('r', 'o', 'g')
('p', 'r', 'o')
('i', 'n', 'g')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g')

Tuple Operations#

1. Changing a Tuple#

Unlike lists, tuples are immutable.

This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like a list, its nested items can be changed.

We can also assign a tuple to different values (reassignment).

# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])

# my_tuple[1] = 9     # ▶ TypeError: 'tuple' object does not support item assignment

# However, item of mutable element can be changed
my_tuple[3][0] = 9    
print(my_tuple)  # ▶ (4, 2, 3, [9, 5])

# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g')
print(my_tuple)  # ▶ ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', ''n', 'g')
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g')

We can use + operator to combine two tuples. This is called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result in a new tuple.

# Example 1:

# Concatenation
print((1, 2, 3) + (4, 5, 6))  # ▶ (1, 2, 3, 4, 5, 6)

# Repeat
print(("Repeat",) * 3)       # ▶ ('Repeat', 'Repeat', 'Repeat')
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
# Example 2:

t1=(1,2,3)
t2=('x','y','z')
t3=t1+t2
print(t3)   # ▶ (1, 2, 3, 'x', 'y', 'z')
print(t1*2) # ▶ (1, 2, 3, 1, 2, 3)
print(t2*3) # ▶ ('x', 'y', 'z', 'x', 'y', 'z', 'x', 'y', 'z')
(1, 2, 3, 'x', 'y', 'z')
(1, 2, 3, 1, 2, 3)
('x', 'y', 'z', 'x', 'y', 'z', 'x', 'y', 'z')
# Example 3:

t1 = (1, 2,3)
t2 = ('abc', 'xyz')

# Following action is not valid for tuples
# t1[0] = 4;
# So let's create a new tuple as follows
t3 = t1 + t2 + ("hey",)  # ∵ () is must when adding or multiply tuples
print (t3)               # ▶ (1, 2, 3, 'abc', 'xyz', 'hey')
(1, 2, 3, 'abc', 'xyz', 'hey')

2. Deleting a Tuple#

As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.

Deleting a tuple entirely, however, is possible using the keyword del.

# Example 1: Deleting tuples

my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g')

# can't delete items
del my_tuple[3]  # ▶ TypeError: 'tuple' object doesn't support item deletion

# Can delete an entire tuple
# del my_tuple
# print(my_tuple)   # ▶ NameError: name 'my_tuple' is not defined
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-f09af94986b4> in <module>
      4 
      5 # can't delete items
----> 6 del my_tuple[3]  # ▶ TypeError: 'tuple' object doesn't support item deletion
      7 
      8 # Can delete an entire tuple

TypeError: 'tuple' object doesn't support item deletion
# Example 2:

t = ('helloWorld', "python", 1, 2.7);
print (t)          # ▶ ('helloWorld', 'python', 1, 2.7)

# can't delete items
del my_tuple[3]  # ▶ TypeError: 'tuple' object doesn't support item deletion

del t
# print ("After deleting t :")  # ▶ After deleting t :
# print (t)                     # ▶ NameError: name 't' is not defined
('helloWorld', 'python', 1, 2.7)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-f3f4b74da706> in <module>
      5 
      6 # can't delete items
----> 7 del my_tuple[3]  # ▶ TypeError: 'tuple' object doesn't support item deletion
      8 
      9 del t

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

Python Built-in Tuple Functions#

Function

Description

len()

Returns number of elements in a tuple.

max()

Returns item from the tuple with max value.

min()

Returns item from the tuple with min value.

sorted()

Returns a new sorted list of sequence in the tuple.

tuple()

Converts a sequence into tuple.

cmp()

Compares items of two tuples. (Not available in Python 3).

len(tuple) - The len() method returns the number of elements in the tuple.#

# Example:

t1= (1,2,3,4,5)
t2 = ('x','y','z',[1,2],3)
print(len(t1))  # ▶ 5
print(len(t2))  # ▶ 5
5
5

max(tuple) - The max() method returns the elements from the tuple with maximum value. Type of element should be same otherwise complier throw TypeError.#

# Example:

t1= (1,2,3,4,5)
t2 = ('x','y','z')
print(max(t1))  # ▶ 5
print(max(t2))  # ▶ z
5
z

min(tuple) - The min() method returns the elements from the tuple with minimum value. Type of element should be same otherwise complier throw TypeError.#

# Example:

t1= (1,2,3,4,5)
t2 = ('x','y','z')
print(min(t1))  # ▶ 1
print(min(t2))  # ▶ x
1
x

sorted(dict) - The sorted() function sorts the elements of a given iterable in a specific order (either ascending or descending) and returns the sorted iterable as a list.#

# vowels tuple
py_tuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(py_tuple))                # ▶ ['a', 'e', 'i', 'o', 'u']
print(sorted(py_tuple, reverse=True))  # ▶ ['u', 'o', 'i', 'e', 'a']
['a', 'e', 'i', 'o', 'u']
['u', 'o', 'i', 'e', 'a']

tuple(seq) - The tuple() method converts a list of items into tuples.#

# Example:

s="helloworld"
t1=tuple(s)
list=[1,2,3]
t2=tuple(list)

print(t1)  # ▶ ('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
print(t2)  # ▶ (1, 2, 3)
('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
(1, 2, 3)

Tuple Methods#

Methods that add items or remove items are not available with tuple. Only the following two methods are available.

Some examples of Python tuple methods:

# Example:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p'))   # ▶  2
print(my_tuple.index('l'))   # ▶  3
2
3

Other Tuple Operations#

1. Tuple Membership Test#

We can test if an item exists in a tuple or not, using the keyword in.

# Example: Membership test in tuple

my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple)      # ▶ True
print('b' in my_tuple)      # ▶ False

# Not in operation
print('g' not in my_tuple)  # ▶ True
True
False
True

2. Iterating Through a Tuple#

We can use a for loop to iterate through each item in a tuple.

# Example: Using a for loop to iterate through a tuple

for name in ('John', 'Kate'):
    print("Hello", name)
Hello John
Hello Kate

Why should we use Tuple? (Advantages of Tuple)#

  • Processing of Tuples are faster than Lists.

  • It makes the data safe as Tuples are immutable and hence cannot be changed.

  • Tuples are used for string formatting.

Advantages of Tuple over List#

Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:

  • We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.

  • Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost.

  • Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.

  • If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.