Python
About Lesson

Tuples are a type of data structure in Python that can store multiple items in a single variable. They are similar to lists, but there are some key differences:

  1. Immutability: Tuples are immutable, meaning once a tuple is created, you cannot change its elements.
  2. Syntax: Tuples use parentheses () while lists use square brackets [].

 

Creating a Tuple

You can create a tuple by placing a sequence of values separated by commas within parentheses.

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

 

Accessing Tuple Elements

You can access elements in a tuple by using indexing, starting from 0.

# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 4

 

Tuple Operations

1. Concatenation

You can concatenate two tuples using the + operator.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)

 

2. Repetition

You can repeat the elements in a tuple using the * operator.

my_tuple = (1, 2, 3)
result = my_tuple * 3
print(result) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

 

Immutability of Tuples

Since tuples are immutable, you cannot change their elements directly. However, you can create a new tuple that includes elements from the existing one.

# Trying to change an element (will raise an error)
# my_tuple[0] = 10 # This will raise a TypeError

# Creating a new tuple with updated values
new_tuple = (10,) + my_tuple[1:]
print(new_tuple) # Output: (10, 2, 3)

 

Tuple Methods

Tuples support only a few methods. Here are the two most commonly used:

1. count(): Returns the number of times a specified value appears in the tuple.

my_tuple = (1, 2, 3, 1, 1, 4)
print(my_tuple.count(1)) # Output: 3

 

2. index(): Returns the index of the first occurrence of a specified value in the tuple.

print(my_tuple.index(3)) # Output: 2

 

Unpacking Tuples

You can unpack a tuple into individual variables.

my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3

 

Nested Tuples

Tuples can contain other tuples as elements.

nested_tuple = (1, (2, 3), (4, (5, 6)))
print(nested_tuple)
print(nested_tuple[1]) # Output: (2, 3)
print(nested_tuple[2][1]) # Output: (5, 6)

Tuples are a useful and efficient way to group related data. They are especially useful when you want to ensure the data remains unchanged throughout the program. While they offer fewer methods than lists, their immutability provides certain performance benefits and can help prevent accidental modification of data.