A Tuple in Python (programming language) is a collection used to store multiple items in a single variable, similar to a list.

However, tuples are immutable, which means their values cannot be changed after creation.

Key Characteristics

  • Ordered
  • Immutable (cannot modify items)
  • Allows duplicate values
  • Faster than lists for fixed data

1️⃣ Creating a Tuple

Tuples are created using parentheses ().

numbers = (1, 2, 3, 4, 5)
print(numbers)

Output

(1, 2, 3, 4, 5)

2️⃣ Tuple with Different Data Types

A tuple can store multiple data types.

data = (10, "Python", 3.14, True)
print(data)

Output

(10, 'Python', 3.14, True)

3️⃣ Accessing Tuple Elements

Items are accessed using index numbers starting from 0.

fruits = ("apple", "banana", "cherry")
print(fruits[0])
print(fruits[1])
print(fruits[2])

Output

apple
banana
cherry

Negative Indexing

print(fruits[-1])

Output

cherry

4️⃣ Tuple Length

Use len() to find the number of items in a tuple.

fruits = ("apple", "banana", "cherry")
print(len(fruits))

Output

3

5️⃣ Tuple with One Item

A comma is required when creating a single-item tuple.

single = ("apple",)
print(type(single))

Output

<class 'tuple'>

Without the comma, Python treats it as a string.


6️⃣ Loop Through a Tuple

You can loop through tuple items using a for loop.

fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)

Output

apple
banana
cherry

7️⃣ Tuple Slicing

You can extract a range of items from a tuple.

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

Output

(2, 3, 4)

8️⃣ Converting Tuple to List

Since tuples cannot be modified, convert them into a list to change values.

fruits = ("apple", "banana", "cherry")

temp = list(fruits)
temp[1] = "orange"

fruits = tuple(temp)

print(fruits)

Output

('apple', 'orange', 'cherry')

9️⃣ Joining Tuples

Two tuples can be combined using the + operator.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

result = tuple1 + tuple2

print(result)

Output

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

πŸ”Ÿ Tuple Packing and Unpacking

Packing

data = ("apple", 10, True)

Unpacking

fruit, number, status = dataprint(fruit)
print(number)
print(status)

Output

apple
10
True

βœ… Summary

FeatureTuple
OrderedYes
MutableNo
Duplicates allowedYes
Syntax( )