Python Tuples

What are Python Tuples?

In Python, a tuple is an immutable sequence of elements. It is similar to a list, but unlike lists, tuples cannot be modified once they are created. Tuples are defined by enclosing a comma-separated sequence of values in parentheses.

Here is an example of a tuple:

my_tuple = (1, 2, 3, 'a', 'b', 'c')

In this example, the tuple my_tuple contains six elements – three integers and three strings.

Accessing Tuple Elements

You can access individual elements of a tuple using indexing, similar to how you access elements in a list. The index of the first element is 0, the second element is 1, and so on. Here is an example:

my_tuple = (1, 2, 3, 'a', 'b', 'c')
print(my_tuple[0])  # Output: 1
print(my_tuple[3])  # Output: 'a'

In this example, we access the first element of the tuple (my_tuple[0]) and the fourth element (my_tuple[3]).

Iterating Over a Tuple

You can use a for loop to iterate over the elements of a tuple. Here is an example:

my_tuple = (1, 2, 3, 'a', 'b', 'c')
for element in my_tuple:
    print(element)

This will output each element of the tuple on a new line:

1
2
3
a
b
c

Tuple Operations

Tuples support various operations, including concatenation and repetition.

Concatenation: You can concatenate two tuples using the ‘+’ operator. Here is an example:

tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)  # Output: (1, 2, 3, 'a', 'b', 'c')

In this example, the tuples tuple1 and tuple2 are concatenated to create a new tuple concatenated_tuple.

Repetition: You can repeat a tuple using the ‘*’ operator. Here is an example:

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

In this example, the tuple my_tuple is repeated three times to create a new tuple repeated_tuple.

Tuple Methods

Tuples have a few built-in methods that allow you to perform operations on them.

count: The count() method returns the number of times a specified element appears in a tuple. Here is an example:

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

In this example, the count() method is used to count the number of occurrences of the element 2 in the tuple my_tuple.

index: The index() method returns the index of the first occurrence of a specified element in a tuple. Here is an example:

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

In this example, the index() method is used to find the index of the element ‘a’ in the tuple my_tuple.

Summary

Tuples are immutable sequences of elements in Python. They can be accessed using indexing and can be iterated over using a for loop. Tuples support concatenation and repetition operations. They also have built-in methods like count() and index() for performing operations on them.

Scroll to Top