Introduction to Tuple in Python

Python : Tuple

A tuple is an ordered, immutable collection of elements enclosed in parentheses () and separated by commas. Once created, it cannot be modified, unlike lists that can be modified.

Creating Tuples:

Creating a tuple is similar to creating a list in Python, but instead of enclosing the elements in square brackets, we use parentheses.

my_tuple = (1, 2, 3, 4)

Accessing Tuple Elements:

We can access individual tuple elements using indexing, just like lists. For example:

my_tuple = (1, 2, 3, 4)
print(my_tuple[0]) # Output: 1

Slicing can also be used to extract a range of elements from a tuple, just like with lists.

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

Tuple Operations:

Although tuples are immutable, we can perform certain operations on them.

Concatenation:

We can concatenate two tuples using the "+" operator, which creates a new tuple with elements from both tuples.

my_tuple_1 = (1, 2, 3)
my_tuple_2 = (4, 5, 6)
my_tuple_3 = my_tuple_1 + my_tuple_2
print(my_tuple_3) # Output: (1, 2, 3, 4, 5, 6)

Repetition:

We can repeat a tuple using the "*" operator, which creates a new tuple with elements repeated a specified number of times.

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

Tuple Methods:

Tuples have two methods: count() and index().

  • count():

The count() method returns the number of times a specified element appears in the tuple.

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

The index() method returns the index of the first occurrence of a specified element in the tuple.

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

Advantages of using Tuples:

  1. Tuples are faster than lists as they are immutable, and their contents cannot be changed, which makes them more efficient.

  2. Tuples can be used as dictionary keys, unlike lists, which cannot be used as keys.

  3. Tuples can be used in situations where the order of the elements is important.

Previous Article

Next Article