TUPLE

Tuples in Python are ordered collections of items, similar to lists. However, unlike lists, tuples are immutable, which means once they are created, their elements cannot be changed, added, or removed. Tuples are defined by enclosing comma-separated values within parentheses ().

Creating a Tuple:

You can create a tuple by enclosing comma-separated values within parentheses ().

my_tuple = (1, 2, 3, 4, 5)

Accessing Elements:

You can access individual elements of a tuple using indexing, similar to lists.

print(my_tuple[0])  # Output: 1
print(my_tuple[-1])  # Output: 5 (Negative indexing starts from the end)

Slicing:

You can extract a sub-tuple (slice) from a tuple using slicing notation [start:stop:step], similar to lists.

print(my_tuple[1:4])  # Output: (2, 3, 4)
print(my_tuple[:3])   # Output: (1, 2, 3) (Start is omitted, defaults to 0)
print(my_tuple[::2])  # Output: (1, 3, 5) (Step is 2, so every second element is selected)

Immutability:

Tuples are immutable, which means you cannot change, add, or remove elements after the tuple has been created.

# This will raise an error
my_tuple[0] = 10

Tuple Packing and Unpacking:

You can pack multiple values into a tuple using comma-separated values, and unpack a tuple into multiple variables.

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

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

Advantages of Tuples:

  • Tuples are faster than lists because they are immutable.
  • Tuples can be used as keys in dictionaries (since they are immutable), while lists cannot.

Tuples are commonly used for storing fixed collections of items, such as coordinates, settings, or configurations, where immutability is desired.

Tuples in Python are immutable, meaning they cannot be modified after creation. Because of this immutability, tuples have fewer built-in methods compared to lists. However, there are still some methods available for tuples:

1. count():

Returns the number of occurrences of a specified value in the tuple.

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

2. index():

Returns the index of the first occurrence of a specified value in the tuple.

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

Tuple Packing and Unpacking:

Although not methods, tuple packing and unpacking are common operations in Python that involve tuples.

  • Tuple Packing: Packing multiple values into a tuple by separating them with commas.
my_tuple = 1, 2, 3
print(my_tuple)  # Output: (1, 2, 3)
  • Tuple Unpacking: Unpacking a tuple into multiple variables.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)  # Output: 1 2 3

These are the primary operations and methods available for tuples in Python. While tuples lack the mutability and some of the flexibility of lists, they are useful for scenarios where immutability is desired, such as representing fixed collections of data.