Python Tuple is an ordered sequence of immutable items.
Tuples are similar to lists, but once created the elements of a tuple can't be changed (tuples are immutable).
Create Python Tuples
A tuple is defined by listing the elements in round brackets ( ), separated by commas.
A tuple can have any number of elements and can be of different types (integer, float, list, string, etc.).
Let's look at the different types of tuples:
my_tuple = ()
print(my_tuple) # ()
my_tuple = (1, 2, 3)
print(my_tuple) # (1, 2, 3)
my_tuple = (1, "a string", 2.3)
print(my_tuple) # (1, 'a string', 2.3)
my_tuple = ("a string", [8, 4, 6], (1, 2, 3))
print(my_tuple) # ('a string', [8, 4, 6], (1, 2, 3))A tuple can also be created without using parentheses. This operation is known as tuple packing.
my_tuple = 1, 2.3, "a string"
print(my_tuple)
a, b, c = my_tuple
print(a) # 1
print(b) # 2.3
print(c) # a stringCreating a tuple with a single element is a bit tricky, because it is not enough to have an element in parentheses: a final comma must be added to indicate that it is a tuple with a single element.
my_tuple = ("a string")
print(type(my_tuple)) # <class 'str'>
my_tuple = ("a string",)
print(type(my_tuple)) # <class 'tuple'>
my_tuple = "a string",
print(type(my_tuple)) # <class 'tuple'>Access Tuple Elements
There are several ways to access items in a tuple.
with Index
The index operator [] can be used to access an item in a tuple.
- In Python, the tuple index starts from 0.
- The index must be an integer. Using values of any other type will result in a
TypeError. - Nested tuples are accessed using nested indexing.
my_tuple = ('t','u','t','o','r','i','a','l')
print(my_tuple[0]) # 't'
print(my_tuple[5]) # 'i'
n_tuple = ("a string", [4, 5, 6], (1, 2, 3))
print(n_tuple[0][3]) # 't'
print(n_tuple[1][1]) # 5with Negative Index
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.
my_tuple = ('t', 'u', 't', 'o', 'r', 'i', 'a', 'l')
print(my_tuple[-1]) # l
print(my_tuple[-4]) # rSlicing
A range of elements in a tuple can be accessed using the slicing operator :.
The possible cases (with examples) are shown in the table below:
| Slice | Description | Example with li=(10,20,30,40) |
|---|---|---|
my_tuple[from:to] |
the elements from from to to-1 |
li[1:3] -> (20,30) |
my_tuple[from:] |
the elements from from to the end of the tuple |
li[2:] -> (30,40) |
my_tuple[:to] |
the elements from the beginning of the tuple to the element to-1 |
li[:3] -> (10,20,30) |
my_tuple[:] |
all elements | li[:] -> (10,20,30,40) |
my_tuple[from:to:step] |
one element each step from from to to-1 |
li[0:3:2] -> (10,30) |
my_tuple[from::step] |
one item each step from from until the end of the tuple |
li[1::2] -> (20,40) |
my_tuple[:to:step] |
one element each step from the beginning to the to-1 element. |
li[:3:2] -> (10,30) |
my_tuple[::step] |
one item each step |
li[::2] -> (10,30) |
Tuple Manipulation
Tuples are immutable, i.e, elements of a tuple can't be modified once assigned.
Change a Tuple
If the element of a tuple is a mutable data type, such as a list, its nested elements can be modified.
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)Tuples can be reassigned to different values (reassignment).
my_tuple = ('t','u','t','o','r','i','a','l')
print(my_tuple) # ('t','u','t','o','r','i','a','l')
my_tuple = (1,2,3, [4,5] ) # reassign
print(my_tuple) # (1,2,3,4,5)Concatenation an Repetition
The + operator is used to combine two tuples. This is called concatenation.
Using the * operator, elements of a tuple can be repeated a specific number of times to create a new tuple.
print((1, 2, 3) + (4, 5, 6)) # (1, 2, 3, 4, 5, 6)
print(("TutRef",) * 3) # ('TutRef', 'TutRef', 'TutRef')Delete a Tuple
As mentioned above, it is not possible to modify the elements of a tuple.
However, it is possible to completely delete a tuple using the del statement
my_tuple = (0, 1, 2, 3, 4, 5)
del my_tuple
print(my_tuple)Other Tuple Operations
Tuple Membership Test
The keyword in is used to check whether an item exists in a tuple.
my_tuple = ['t','u','t','o','r','i','a','l']
print('t' in my_tuple) # True
print('e' in my_tuple) # False
print('c' not in my_tuple) # TrueIterating Through a Tuple
Using a for loop, it is possible to iterate each element of a tuple.
for color in ('red','blue','yellow'):
print("I'm wearing a", color, "t-shirt")Output
I'm wearing a red t-shirt
I'm wearing a blue t-shirt
I'm wearing a yellow t-shirtSummary of Python Tuple Methods
| Method | Description |
|---|---|
count() |
returns the count of the number of items passed as an argument |
index() |
returns the index of the first matched item |
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3