A tuple in Python is a collection data type that is ordered and immutable, meaning its elements cannot be changed or modified once the tuple is created. Tuples are similar to lists but have some key differences:

  • Immutable: You cannot change, add, or remove elements from a tuple after it is created.
  • Ordered: The items in a tuple have a defined order and can be accessed by their index.
  • Heterogeneous: Tuples can store elements of different data types, such as integers, strings, lists, etc.

Creating a Tuple

Tuples are created by placing a comma-separated list of items inside parentheses (). For example:

# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
Accessing Tuple Elements

You can access elements in a tuple using indexing, with the first element at index

# Accessing elements of a tuple
print(my_tuple[0])  # Output: 1
print(my_tuple[1])  # Output: 2
Tuple Slicing

You can also access a range of elements using slicing:

# Slicing a tuple
print(my_tuple[1:4])  # Output: (2, 3, 4)
Tuple vs. List
  • List: Mutable (can be modified).
  • Tuple: Immutable (cannot be modified).
  • Performance: Tuples are generally faster than lists because they are immutable.
Example of Creating and Using Tuples:
# Tuple creation
person = ("John", 25, "Engineer")

# Accessing elements
name = person[0]  # "John"
age = person[1]   # 25
occupation = person[2]  # "Engineer"

# Nested tuple
nested_tuple = (1, 2, (3, 4))

print(nested_tuple[2][1])  # Output: 4
Tuple Methods

While tuples are immutable, they do have some built-in methods like:

  • .count(): Counts the occurrences of an element in the tuple.
  • .index(): Finds the index of the first occurrence of an element.
my_tuple = (1, 2, 3, 2, 4)
print(my_tuple.count(2))  # Output: 2
print(my_tuple.index(3))  # Output: 2