Tuple & Tuple Methods in Python

Comprehensive Guide to Python Tuples

1. Introduction to Tuples in Python

A tuple can be written as a collection of comma-separated values enclosed within parentheses (). Because they are immutable, they are perfect for storing data that should not be altered throughout the life of a program.

Python Code - Empty Tuple
t1 = ()
print(t1)
Output
()
Python Code - Mixed Data Types
t2 = (123, "python", 3.7)
print(t2)
Output
(123, 'python', 3.7)
Python Code - Numbers
t3 = (1, 2, 3, 4, 5, 6)
print(t3)
Output
(1, 2, 3, 4, 5, 6)
Python Code - Single Element Tuple
t4 = ("C",)
print(t4)
Output
('C',)

2. Tuple Indexing

Like lists, tuple indexing starts from 0. Elements can be accessed using the slice operator [].

Python Code - Forward Indexing (0th Element)
mytuple = ('banana', 'apple', 'mango', 'tomato', 'berry')
print(mytuple[0])
Output
banana
Python Code - Forward Indexing (2nd Element)
mytuple = ('banana', 'apple', 'mango', 'tomato', 'berry')
print(mytuple[2])
Output
mango
Python Code - Forward Slicing
mytuple = ('banana', 'apple', 'mango', 'tomato', 'berry')
print(mytuple[1:3])
Output
('apple', 'mango')

Negative Indexing

Python allows the use of negative indexing. The negative indices are counted from the right side, starting at -1.

Python Code - Negative Indexing (-1)
mytuple = ('banana', 'apple', 'mango', 'tomato', 'berry')
print(mytuple[-1])
Output
berry
Python Code - Negative Indexing (-3)
mytuple = ('banana', 'apple', 'mango', 'tomato', 'berry')
print(mytuple[-3])
Output
mango
Python Code - Negative Slicing
mytuple = ('banana', 'apple', 'mango', 'tomato', 'berry')
print(mytuple[-4:-2])
Output
('apple', 'mango')

3. Tuple Operators

You can manipulate tuples using operators like + (Concatenation), * (Repetition), and check for elements using in or not in (Membership).

Python Code - Concatenation (+)
num = (1, 2, 3, 4, 5)
lang = ('python', 'c', 'java', 'php')

print(num + lang)
Output
(1, 2, 3, 4, 5, 'python', 'c', 'java', 'php')
Python Code - Repetition (*)
num = (1, 2, 3, 4, 5)

print(num * 2)
Output
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Python Code - Membership (in)
lang = ('python', 'c', 'java', 'php')

print('cpp' in lang)
Output
False
Python Code - Membership (not in)
num = (1, 2, 3, 4, 5)

print(6 not in num)
Output
True

🧠 Pop Quiz 1: Tuple Syntax

Question: How do you define a tuple with exactly one element, the string "Hello"?

Click here to reveal the answer

Answer: ("Hello",)

Explanation: The trailing comma is mandatory. Without the comma, Python treats ("Hello") simply as a string surrounded by parentheses.

4. Adding or Removing Elements

Unlike lists, the tuple items cannot be updated or deleted as tuples are immutable.

Python Code - Attempting to Update an Item
tup = ('python', 'c', 'java', 'php')
tup[3] = "html"
Output
TypeError: 'tuple' object does not support item assignment

To delete an entire tuple, we can use the del keyword with the tuple name.

Python Code - Deleting a Tuple
tup = ('python', 'c', 'java', 'php')
del tup

# If we try to print(tup) now, it will raise a NameError.
Output
# Tuple 'tup' has been completely removed from memory.

5. Iterating a Tuple

A tuple can be iterated by using a standard for in loop.

Python Code - Iterating
lang = ('python', 'c', 'java', 'php')
print("The tuple items are \n")

for i in lang:
    print(i)
Output
The tuple items are python c java php

🧠 Pop Quiz 2: Mutability

Question: True or False: You can use the remove() method to take an item out of a tuple.

Click here to reveal the answer

Answer: False.

Explanation: Tuples are immutable, meaning they cannot be changed after creation. Methods like append(), insert(), remove(), and pop() do not exist for tuples.

6. Tuple Functions & Methods

Python provides various built-in functions that work on tuples, such as finding lengths, maximums, and minimums. Since tuples can't be changed, they only have two specific methods: count() and index().

Python Code - len()
num = (1, 2, 3, 4, 5, 6)

print("length of tuple :", len(num))
Output
length of tuple : 6
Python Code - max()
t1 = (1, 2, 3, 4, 5, 6)
t2 = ('java', 'c', 'python', 'cpp')

print("Max of Tuple t1 :", max(t1))
print("Max of Tuple t2 :", max(t2))
Output
Max of Tuple t1 : 6 Max of Tuple t2 : python
Python Code - min()
t1 = (1, 2, 3, 4, 5, 6)
t2 = ('java', 'c', 'python', 'cpp')

print("Min of Tuple t1 :", min(t1))
print("Min of Tuple t2 :", min(t2))
Output
Min of Tuple t1 : 1 Min of Tuple t2 : c
Python Code - sum()
t1 = (1, 2, 3, 4, 5, 6)

print("Sum of tuple items :", sum(t1))
Output
Sum of tuple items : 21
Python Code - tuple() conversion
str_val = "python"
t1 = tuple(str_val)
print(t1)

num_list = [1, 2, 3, 4, 5, 6]
t2 = tuple(num_list)
print(t2)
Output
('p', 'y', 't', 'h', 'o', 'n') (1, 2, 3, 4, 5, 6)
Python Code - sorted()
num = (1, 3, 2, 4, 6, 5)
lang = ('java', 'c', 'python', 'cpp')

print(sorted(num))
print(sorted(lang))
Output
[1, 2, 3, 4, 5, 6] ['c', 'cpp', 'java', 'python']
Python Code - count()
num = (1, 2, 3, 4, 3, 2, 2, 1, 4, 5, 8)

cnt = num.count(2)
print("Count of 2 is:", cnt)

cnt = num.count(10)
print("Count of 10 is:", cnt)
Output
Count of 2 is: 3 Count of 10 is: 0
Python Code - index()
t1 = ('p', 'y', 't', 'o', 'n', 'p')

print(t1.index('t'))
print(t1.index('p'))
print(t1.index('p', 3, 10)) # Search for 'p' between index 3 and 10
Output
2 0 5

🧠 Pop Quiz 3: Functions vs Methods

Question: When you use sorted() on a tuple, what data type does it return?

Click here to reveal the answer

Answer: A List.

Explanation: Because tuples cannot be modified in place, the sorted() function takes the elements of the tuple, sorts them, and returns them as a brand new list (e.g., [1, 2, 3] instead of (1, 2, 3)).

Post a Comment

0 Comments