A tuple is a built-in Python data type that represents an ordered, immutable collection of elements.
Key Features:
Ordered: Elements have a defined order (you can access by index).
Immutable: Once created, elements cannot be changed.
Allows duplicates: Same value can appear more than once.
Can contain mixed data types (integers, strings, lists, etc.).
# Empty tuple
t1 = ()
# Tuple with elements
t2 = (1, 2, 3)
# Tuple with mixed data types
t3 = ('a', 2, 3.5)
print(t3)
# output
# ('a', 2, 3.5)
# Tuple without parentheses
t4 = 1, 2, 3
print(t4)
# output:
# (1, 2, 3)
t5 = (6) # This is just an integer, not a tuple
print("t5=",t5)
# output:
# t5= 6
t6 = (6,) # This is a tuple with one element
print("t6=",t6)
# output:
# t6= (6,)
#Iteration over a Tuple:
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
# output:
# red
# green
# blue
# Tuple Packing and Unpacking:
# Packing
point = (6, 7)
# Unpacking
x, y = point
print(x) # 6
print(y) # 7
new_tuple = (1, 2, 3, 2,4,2,5)
print("Length of tuple=",len(new_tuple))
print("No of occurance of 2 in the tuple=",new_tuple.count(2))
print("Item at 3rd index =",new_tuple.index(3))
# output
# Length of tuple= 7
# No of occurance of 2 in the tuple= 3
# Item at 3rd index = 2
# tuple is immutable i.e. you can not assign item to the tuple .The below code will throw error.
new_tuple[0]=70
# Error:
# Traceback (most recent call last):
# File "c:\Users\Admin\OneDrive\Documents\Python Scripts\script_tuple.py", line 67, in <module>
# new_tuple[0]=70
# ~~~~~~~~~^^^
# TypeError: 'tuple' object does not support item assignment