Skip to content

Creating a tuple:

# Creating a tuple
numbers = (1, 2, 3, 4, 5)

# Printing the tuple
print(numbers)

Accessing tuple elements:

# Creating a tuple
colors = ('red', 'green', 'blue')

# Accessing elements of a tuple
print(colors[0])  # 'red'
print(colors[1])  # 'green'
print(colors[2])  # 'blue'

Modifying tuple elements:

# Creating a tuple
numbers = (1, 2, 3, 4, 5)

# Modifying tuple elements is not allowed
try:
numbers[0] = 10
except TypeError as e:
print(e)

Deleting tuple elements:

# Creating a tuple
numbers = (1, 2, 3, 4, 5)

# Deleting tuple elements is not allowed
try:
del numbers[0]
except TypeError as e:
print(e)

Tuple concatenation:

# Creating two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Concatenating two tuples
tuple3 = tuple1 + tuple2
print(tuple3)  # (1, 2, 3, 4, 5, 6)

Tuple repetition:

# Creating a tuple
tuple1 = (1, 2, 3)

# Repeating the tuple
tuple2 = tuple1 * 3
print(tuple2)  # (1, 2, 3, 1, 2, 3, 1, 2, 3)

Tuple membership:

# Creating a tuple
tuple1 = (1, 2, 3, 4, 5)

# Checking membership in a tuple
print(1 in tuple1)  # True
print(6 in tuple1)  # False

Tuple iteration:

# Creating a tuple
tuple1 = (1, 2, 3, 4, 5)

# Iterating over a tuple
for x in tuple1:
print(x)

Tuple unpacking:

# Creating a tuple
tuple1 = (1, 2, 3)

# Unpacking a tuple
a, b, c = tuple1
print(a)  # 1
print(b)  # 2
print(c)  # 3

Tuple packing and unpacking:

# Packing values into a tuple
tuple1 = 1, 2, 3

# Unpacking a tuple
a, b, c = tuple1

# Repacking values into a new tuple
tuple2 = a, c
print(tuple2)  # (1, 3)