0% completed
A tuple in Python is an immutable sequence, meaning its contents cannot be modified after creation. Tuples allow storing multiple values in a single variable, similar to lists, but with the added advantage of immutability. This makes them ideal for scenarios where data integrity is crucial, such as fixed configurations, database records, and thread-safe operations.
Since tuples are faster than lists (due to their immutability) and require less memory, they are commonly used when working with read-only data that should not be altered during execution.
Tuples are created by placing a sequence of values separated by commas. Parentheses ()
are optional but commonly used for readability. This is known as tuple packing, where multiple values are grouped into a tuple.
A tuple can be defined using parentheses or simply by separating values with commas.
my_tuple
explicitly uses parentheses, making it clear that it is a tuple.another_tuple
does not use parentheses, but Python automatically recognizes it as a tuple due to comma separation.An empty tuple is a tuple with no elements. It is useful when a placeholder is needed for future data storage.
()
define an empty tuple with no elements.A tuple with one element must include a trailing comma after the element. Without this comma, Python treats it as a regular variable instead of a tuple.
single_element_tuple = (42,)
correctly defines a one-element tuple using a trailing comma.not_a_tuple = (42)
is interpreted as an integer inside parentheses, not a tuple.To ensure Python recognizes a single-element tuple, always include a comma after the value.
.....
.....
.....