TUPLES
M3-R5.1 · Chapter 5: Sequence Data Types · 9 min read
Python Tuples
1. Introduction to Tuples
A tuple is a sequence of immutable objects in Python. It is similar to a list, but with one key difference: tuples cannot be changed (modified) once created. Lists use square brackets [ ], whereas tuples use parentheses ( ).
Key characteristics:
- Ordered – elements maintain their insertion order
- Immutable – cannot be changed, added to, or removed from after creation
- Allows duplicates – multiple identical values are permitted
- Can hold mixed data types – integers, floats, strings, lists, even nested tuples
- Indexed – zero-based indexing, just like lists
2. Creating a Tuple
Syntax:
tuple_name = (value1, value2, value3, ...)
A tuple is created by placing items inside parentheses (), separated by commas. The parentheses are optional, but it is good practice to use them.
Examples
# Empty tuple
my_tuple = ()
# Tuple with integers
my_tuple = (1, 2, 3)
# Tuple with mixed data types
my_tuple = (1, 'Hello', 3.4)
# Nested tuple
my_tuple = ('mouse', [8, 4, 6], (1, 2, 3))
# Tuple without parentheses (packing)
my_tuple = 3, 4.6, 'dog'
# Single-element tuple (note the trailing comma!)
T5 = (90,) # Without comma: (90) is just an integer
Important: To create a single-element tuple, always add a trailing comma, e.g. (90,). Without it, Python treats it as a plain value.
3. Tuple Unpacking
Tuple unpacking allows assigning tuple values to multiple variables in a single statement.
my_tuple = 3, 4.6, 'dog'
a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog
4. Accessing Tuple Elements
4.1 Positive Indexing
The index operator [] is used to access elements. Indexing starts at 0.
tup = ('p', 'e', 'r', 'm', 'i', 't')
print(tup[0]) # p
print(tup[5]) # t
# print(tup[6]) --> IndexError: index out of range
|
Positive Index |
0 |
1 |
2 |
3 |
4 |
|
Value |
C |
CPP |
JAVA |
PHP |
PYTHON |
|
Negative Index |
-5 |
-4 |
-3 |
-2 |
-1 |
4.2 Negative Indexing
Python supports negative indexing. -1 refers to the last item, -2 to the second last, and so on.
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-1]) # t
print(my_tuple[-6]) # p
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16)
print(tupl3[-6:-2]) # (6, 8, 10, 12, 14)
4.3 Slicing
Use the range slice operator [:] to access a range of elements.
tup2 = (5, 11, 22, 44, 9, 66)
print(tup2[1:5]) # (11, 22, 44, 9)
# Nested tuple access
ntup = ('mouse', [8, 4, 6], (1, 2, 3))
print(ntup[0][3]) # s (4th character of 'mouse')
print(ntup[1][1]) # 4 (2nd element of inner list)
5. Updating Tuples
Tuples are immutable — individual elements cannot be changed directly. However, you can create a new tuple by joining existing ones.
tupl1 = (2, 3, 4)
tupl2 = ('ab', 'cd')
tupl3 = tupl1 + tupl2
print(tupl3) # (2, 3, 4, 'ab', 'cd')
6. Deleting Tuple Elements
Direct deletion of individual tuple elements is not possible. To simulate deletion, create a new tuple with only the desired elements using slicing.
tup1 = (1, 2, 3)
tup3 = tup1[0:1] + tup1[2:] # Skips index 1
print(tup3) # (1, 3)
To delete an entire tuple, use the del statement:
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16)
del tupl3
# print(tupl3) --> NameError: name 'tupl3' is not defined
7. Iterating Through a Tuple
Tuple elements can be accessed sequentially using loops.
Method 1: Using for loop directly
tuple = ('apple', 'banana', 'cherry')
for x in tuple:
print(x)
# Output: apple banana cherry
Method 2: Using range and index
tuple = ('apple', 'banana', 'cherry')
for i in range(len(tuple)):
print(tuple[i])
# Output: apple banana cherry
8. Basic Tuple Operations
|
Operator |
Name |
Description |
Example |
Result |
|
+ |
Concatenation |
Joins two tuples |
(1,2) + (4,5) |
(1, 2, 4, 5) |
|
* |
Repetition |
Repeats a tuple n times |
('CS',) * 2 |
('CS', 'CS') |
|
[] |
Slice |
Accesses element by index |
lang[2] |
java |
|
[:] |
Range Slice |
Accesses a range of items |
lang[1:4] |
('c','java','php') |
|
in |
Membership |
Checks presence in tuple |
'cpp' in lang |
True / False |
|
not in |
Not Membership |
Checks absence in tuple |
6 not in num |
True / False |
|
len() |
Length |
Number of items in tuple |
len((1, 2)) |
2 |
Example:
num = (1, 2, 3, 4, 5)
lang = ('python', 'c', 'java', 'php')
print(num + lang) # (1,2,3,4,5,'python','c','java','php')
print(num * 2) # (1,2,3,4,5,1,2,3,4,5)
print(lang[2]) # java
print(lang[1:4]) # ('c', 'java', 'php')
print('cpp' in lang) # False
print(6 not in num) # True
9. Built-in Tuple Functions
|
Function |
Syntax |
Description |
|
len() |
len(tuple) |
Returns the number of items in the tuple |
|
max() |
max(tuple) |
Returns the largest item in the tuple |
|
min() |
min(tuple) |
Returns the smallest item in the tuple |
|
sorted() |
sorted(tuple, reverse=False) |
Returns a sorted list from the tuple (ascending by default) |
|
tuple() |
tuple(sequence) |
Converts a sequence (list, string) into a tuple |
|
sum() |
sum(tuple) |
Returns the sum of all numeric elements |
|
count() |
tuple.count(x) |
Returns the number of times x appears in the tuple |
|
index() |
tuple.index(x) |
Returns the index of the first occurrence of x |
Examples:
num = (1, 2, 3, 4, 5, 6)
lang = ('java', 'c', 'python', 'cpp')
print(len(num)) # 6
print(max(num)) # 6
print(min(num)) # 1
print(sorted(num)) # [1, 2, 3, 4, 5, 6]
print(sorted(lang)) # ['c', 'cpp', 'java', 'python']
print(sorted(num, reverse=True)) # [6, 5, 4, 3, 2, 1]
# tuple() conversion
str1 = 'python'
tup1 = tuple(str1) # ('p','y','t','h','o','n')
lst = [1, 2, 3, 4, 5]
tup2 = tuple(lst) # (1, 2, 3, 4, 5)
10. Linear Search in a Tuple
Linear search checks each element one by one to find if a target value exists in the tuple.
Tuple = (1, 2, 3, 4, 5, 6)
n = 5
B = False
for i in range(len(Tuple)):
if Tuple[i] == n:
B = True
if B == True:
print('Found')
else:
print('Not Found')
# Output: Found
11. Counting Frequency of Elements
This program counts how many times each element appears in a tuple.
x = (1, 2, 8, 3, 2, 2, 2, 5, 1)
arr = list(x)
fr = [None] * len(arr)
visited = -1
for i in range(0, len(arr)):
count = 1
for j in range(i+1, len(arr)):
if arr[i] == arr[j]:
count = count + 1
fr[j] = visited
if fr[i] != visited:
fr[i] = count
print('Element | Frequency')
for i in range(0, len(fr)):
if fr[i] != visited:
print(str(arr[i]) + ' | ' + str(fr[i]))
12. Fibonacci Series Stored in a Tuple
Tuples can be built dynamically by concatenating single-element tuples in a loop.
nterms = 10
n1, n2 = 0, 1
count = 0
tup = ()
if nterms <= 0:
print('Please enter a positive integer')
elif nterms == 1:
print('Fibonacci sequence:', n1)
else:
while count < nterms:
tup = tup + (n1,)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
print(tup)
# Output: (0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
13. Tuple vs List – Quick Comparison
|
Feature |
Tuple |
List |
|
Syntax |
( ) |
[ ] |
|
Mutability |
Immutable (cannot change) |
Mutable (can change) |
|
Speed |
Faster |
Slower |
|
Memory |
Less memory |
More memory |
|
Use Case |
Fixed/constant data |
Dynamic/changing data |
|
Methods |
count(), index() |
append(), remove(), pop(), etc. |
|
Hashable? |
Yes (can be dict key) |
No |
14. Common Errors with Tuples
|
Error |
Cause |
Example |
|
IndexError |
Accessing index out of range |
tup[10] on a 6-element tuple |
|
TypeError |
Using float/non-integer as index |
tup[2.0] |
|
TypeError |
Trying to modify a tuple |
tup[0] = 'new' |
|
NameError |
Using deleted tuple |
del tup; print(tup) |
End of Notes – Python Tuples