In Python, a tuple is an ordered collection of elements, similar to a list, but unlike lists, tuples are immutable, meaning their elements cannot be changed after creation.
Tuples are created by enclosing comma-separated elements within parentheses ().
Here's how to work with tuples in Python:
# define tuple variable, it accept comma separted value inside () parentheses. varname = (value1, value2)
We can create a tuple by enclosing elements within parentheses.
your_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9) # printing tuple values print(your_tuple) # Output: (1, 2, 3, 4, 5, 6, 7, 8, 9) # checking type of variable print(type(your_tuple)) # Output: <class 'tuple'>
your_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9) print(your_tuple[2]) # Output: 3 print(your_tuple[5]) # Output: 6 # If try to access the index which is not exist, it will throw error. print(your_tuple[10]) # Output: tuple index out of range
We can access elements of a tuple using their indices, similar to lists.
your_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9) # This will raise a TypeError your_tuple[0] = 10 # Output: 'tuple' object does not support item assignment
Tuples are immutable, so we cannot modify their elements after creation. It will throw an error: 'tuple' object does not support item assignment.
# Tuple packing your_tuple = 1, 2, 3 # Tuple unpacking a, b, c = your_tuple print(a, b, c) # Output: 1 2 3
single_tuple = (1,)
We can assign multiple values to a single tuple and also unpack the values of a tuple into individual variables.
empty_tuple = ()
To create a single-element tuple, we need to include a trailing comma after the element.
tuple1 = (1, 2) tuple2 = (3, 4) # Concatenation concatenated_tuple = tuple1 + tuple2 print(concatenated_tuple) # Output: (1, 2, 3, 4) # Repetition repeated_tuple = tuple1 * 3 print(repeated_tuple) # Output: (1, 2, 1, 2, 1, 2) # Checking value exist in tuple print(1 in tuple1) # Output: True print(5 in tuple1) # Output: False
An empty tuple is created using empty parentheses "()".
Tuples support various operations such as tuple concatenation, values repetition, and checking elements exists in a tuple.
Example 1: `+` operator will concat values of both tuples into new variable.
Example 2: `*` with `N` will return repeated values of original tuples `N` times.
Example 3: the `in` keyword is used to check value exists in tuple.
Tuples are often used in Python for representing fixed collections of items, such as coordinates, database records, and function return values.
Their immutability provides safety against accidental changes and makes them suitable for use cases where data should not be modified after creation.