Sequence Data types part 3 – Tuples

Tuples

In Python, tuples are an ordered and immutable sequence of items. This means that once you create a tuple, its values cannot be changed, and the order of items remains fixed. Tuples are incredibly useful when you need to store a collection of related values that should not be modified during your program’s execution.

Creating Tuples

Tuple Literals:

The simplest way to create a tuple is by enclosing a comma-separated sequence of items within parentheses:

my_tuple = (10, 20, ‘apple’, 3.14)

print(my_tuple)   # Output: (10, 20, ‘apple’, 3.14)

my_tuple is a variable assigned a tuple containing integer, string, and float values.

Commas are essential, even when creating a tuple with a single item.

Explicit Typecasting (The tuple() Constructor):

You can create a tuple by passing any iterable (like a list or string) to the tuple() constructor:

numbers = [1, 2, 3, 4]

numbers_tuple = tuple(numbers)

print(numbers_tuple)  # Output: (1, 2, 3, 4)

The tuple() function converts the numbers list into a tuple.

Singleton Tuples:

To create a tuple with just one element, you need to include a trailing comma:

singleton_tuple = (5,) 

print(singleton_tuple)  # Output: (5,)

The comma after 5 is essential to differentiate the tuple from a parenthesized expression.

Indexing and Accessing Elements

Tuples are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. You can access elements using square brackets:

fruits = (‘apple’, ‘banana’, ‘orange’)

print(fruits[1])   # Output: banana (Positive index)

print(fruits[-2])  # Output: banana (Negative index)

Positive indexing: Starts from 0 (the beginning) of the tuple.

Negative indexing: Starts from -1 (the end) of the tuple.

IndexError: Trying to access an index beyond the tuple’s length results in an IndexError.

Membership Testing

You can use the in and not in operators to check if a value exists within a tuple:

colors = (‘red’, ‘green’, ‘blue’)

print(‘yellow’ in colors)   # Output: False

print(‘green’ not in colors) # Output: False

len() Function

The len() function returns the number of elements in a tuple:

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

print(len(numbers))  # Output: 5

Immutability

Tuples are immutable, meaning their elements cannot be changed once created:

numbers = (1, 2, 3)

numbers[0] = 10   # Raises a TypeError (tuples are immutable)

Tuple Slicing

Slicing allows you to extract a portion of a tuple.

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

print(my_tuple[2:5])  # Output: (3, 4, 5) 

The slice notation [start:end] creates a new tuple containing elements from index start up to, but not including, index end.

Concatenation

tuple1 = (1,2,3)

tuple2 = (4,5,6)

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

The + operator concatenates two tuples to create a new tuple.

Nested Tuples

Tuples can contain other tuples:

nested_tuple = (1, 2, (‘a’, ‘b’), 3)

print(nested_tuple[2][1])   # Output: b (accessing ‘b’ in the inner tuple)

Looping Through Tuples

colors = (‘red’, ‘green’, ‘blue’)

for color in colors:

    print(color)

Output: red green blue

The enumerate() Function

The enumerate() function allows you to iterate over a tuple while getting both the index and value of each element:

colors = (‘red’, ‘green’, ‘blue’)

for index, color in enumerate(colors):

    print(f”Index {index}: {color}”)

Tuple Methods

count(x):

The count(x) method returns the number of times the value x appears within the tuple.

numbers = (1, 2, 3, 2, 5, 2)

count_of_two = numbers.count(2) 

print(count_of_two)  # Output: 3

numbers.count(2) is called to find how many times the value 2 appears in the tuple numbers.

The result, 3, is stored in count_of_two and then printed.

index(x):

The index(x) method returns the index (position) of the first occurrence of the value x within the tuple. If the value isn’t found, it raises a ValueError.

fruits = (‘apple’, ‘banana’, ‘orange’, ‘banana’)

banana_index = fruits.index(‘banana’)

print(banana_index)   # Output: 1

fruits.index(‘banana’) is called to find the index of the first ‘banana’ in the tuple.

The index, 1, is stored in banana_index and then printed.

Important Note: Since tuples are ordered, the index() method always returns the index of the leftmost occurrence of the value.