What is a tuple in Python?
a) An ordered and immutable collection of items
b) A mutable collection of key-value pairs
c) A set of unique, unordered elements
d) A list with duplicate values
Answer:
a) An ordered and immutable collection of items
Explanation:
A tuple in Python is an ordered and immutable collection of items. Once a tuple is created, its elements cannot be changed, added, or removed. Tuples are often used to group related data and are useful when you want to ensure that the data remains constant throughout the program.
# Example of a tuple
coordinates = (10, 20, 30)
print(coordinates[0]) # Output: 10
# Attempting to modify a tuple will raise an error
# coordinates[0] = 40 # TypeError: 'tuple' object does not support item assignment
In this example, the tuple coordinates
contains three integers. Tuples are indexed like lists, but they do not allow modification of their elements.
Tuples are ideal for storing data that should not be altered, such as geographic coordinates, RGB color values, or any other grouped data that needs to remain constant.