Tuples are similar to lists, but they are immutable, meaning that their values cannot be changed once they are created. They are typically used to group related values together, such as coordinates or RGB color values.
To create a tuple in Python, you can simply use parentheses to enclose a comma-separated sequence of values:
coordinates = (3, 4) colors = ('red', 'green', 'blue')
You can access individual elements of a tuple using indexing, just like with lists:
print(coordinates) # 3 print(colors) # 'green'
You can also use slicing to extract a subset of a tuple:
print(colors[1:]) # ('green', 'blue')
Tuple assignment is a useful technique in Python that allows you to assign multiple variables at once:
x, y = coordinates print(x) # 3 print(y) # 4
You can also use tuples as return values from functions:
def divide_and_remainder(a, b): quotient = a // b remainder = a % b return (quotient, remainder) result = divide_and_remainder(10, 3) print(result) # (3, 1)
Finally, you can use the
len() function to get the length of a tuple:
print(len(colors)) # 3