A tuple in Python is an ordered, immutable collection of items, enclosed in parentheses ( ). Like lists, tuples can store elements of different data types, but unlike lists, tuples cannot be changed after creation.
Thank you for reading this post, don't forget to subscribe!Updating Tuples:
Since tuples are immutable, you cannot directly change their values. To update a tuple, you must convert it to a list, make changes, and convert it back to a tuple.
Example:
t = (1, 2, 3)
temp = list(t)
temp[0] = 100
t = tuple(temp)
print(t) # Output: (100, 2, 3)Indexing and Slicing:
You can access individual elements or slices of a tuple, just like with lists.
Example:
t = (10, 20, 30, 40)
print(t[1]) # Output: 20
print(t[1:3]) # Output: (20, 30)Unpacking Tuples:
Tuple unpacking allows you to assign the values of a tuple to individual variables in a single step.
Example:
a, b = (5, 10)
print(a) # Output: 5
print(b) # Output: 10Looping Through a Tuple:
You can use a loop to iterate over the items in a tuple.
Example:
t = ('apple', 'banana', 'cherry')
for item in t:
print(item)Joining Tuples:
Tuples can be joined (concatenated) using the + operator.
Example:
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3) # Output: (1, 2, 3, 4)