Tuples

Home / Python / Tuples

Tuples


1. What are Tuples?
  • A tuple in Python is similar to a list, but unlike lists, tuples are immutable. Once a tuple is created, its values cannot be changed, modified, or updated.
  • Tuples are used to store a collection of items, and are defined using parentheses () instead of square brackets.
  • Tuples can hold different data types such as integers, strings, or even other tuples.
my_tuple = (1, "apple", 3.5)
2. Immutability of Tuples
  • Immutability means that after a tuple is created, you cannot modify (add, remove, or change) its elements.
  • This immutability provides some advantages, such as improved performance and safety when working with data that shouldn’t be changed accidentally.
  • If you try to modify an element of a tuple, Python will raise an error:
my_tuple = (10, 20, 30)
my_tuple[1] = 25 # This will raise a TypeError
3. Creating a Tuple
Tuples are created by placing values within parentheses, separated by commas.
my_tuple = (1, 2, 3)
You can create a tuple with a single element by adding a trailing comma after the element. Without the comma, Python will treat it as a regular value.
single_element_tuple = (5,)        # Correct
not_a_tuple = (5)                  # Just an integer, not a tuple
single_string_tuple = ("saksham",) # Correct
not_a_tuple = ("saksham")          #Just a string, not a tuple
Without parentheses: Python also allows creating tuples without using parentheses (just by separating values with commas), though it is less common and not recommended for clarity.
my_tuple = 1, 2, 3
Empty tuple: You can create an empty tuple using empty parentheses.
empty_tuple = ()
4. Accessing Tuples
Tuples support indexing and slicing just like lists and strings.
Indexing: Use square brackets to access elements of the tuple by their position, starting from 0 (zero-based indexing).
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0])  # Output: "apple"
print(my_tuple[2]) # Output: "cherry"
Negative indexing: Negative indexes allow you to access elements from the end of the tuple.
print(my_tuple[-1]) # Output: "cherry" (last element)
print(my_tuple[-2])  # Output: "banana" (second last element)
Slicing: You can extract a subset of a tuple using slicing. The syntax is [start:end:step].
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[1:4]) # Output: (20, 30, 40)
print(my_tuple[:3])   # Output: (10, 20, 30)
print(my_tuple[::2]) # Output: (10, 30, 50) (every second element)
Tuple unpacking: You can assign each element of a tuple to variables in one line using tuple unpacking.
point = (4, 5)
x, y = point
print(x) # Output: 4
print(y) # Output: 5