Python From Beginner to Advanced

0% completed

Previous
Next
Python - Tuple Operators

Tuples in Python support various operators that allow performing common operations such as concatenation, repetition, and membership testing. These operators work similarly to list operations but respect the immutability of tuples, meaning they create new tuples rather than modifying existing ones.

Using tuple operators helps in combining data, repeating elements, and checking for values efficiently without altering the original tuple.

1. Tuple Concatenation ("+" Operator)

The + operator allows joining two tuples together to form a new tuple. Since tuples are immutable, concatenation does not modify the original tuples but instead creates a new tuple.

Example 1: Concatenating Two Tuples

Python3
Python3

. . . .

Explanation

  • tuple1 + tuple2 creates a new tuple by appending the elements of tuple2 to tuple1.
  • The original tuples remain unchanged since tuples are immutable.

2. Tuple Repetition ("*" Operator)

The * operator repeats the contents of a tuple a specified number of times, creating a new tuple.

Example 2: Repeating a Tuple

Python3
Python3

. . . .

Explanation

  • numbers * 3 creates a new tuple where the contents of numbers are repeated three times.
  • This operation does not modify the original tuple but instead returns a new tuple with repeated elements.

3. Membership Testing ("in" and "not in" Operators)

The in operator checks whether an element exists in a tuple, while not in checks whether an element does not exist. These operators return True or False based on the presence of the element.

Example 3: Checking if an Element Exists in a Tuple

Python3
Python3

. . . .

Explanation

  • "banana" in fruits returns True because "banana" is present in the tuple.
  • "grape" in fruits returns False because "grape" is not in the tuple.

Example 4: Checking if an Element is Not in a Tuple

Python3
Python3

. . . .

Explanation

  • "yellow" not in colors returns True because "yellow" is not present in the tuple.
  • "red" not in colors returns False because "red" exists in the tuple.

Python provides four key operators that work with tuples:

OperatorDescriptionExample Usage
+Concatenates two tuples into a new tuple.tuple1 + tuple2
*Repeats the tuple’s elements a given number of times.tuple1 * 3
inChecks if an element exists in the tuple."apple" in tuple1
not inChecks if an element does not exist in the tuple."grape" not in tuple1

Each of these operations ensures that tuples remain immutable, allowing efficient manipulation of tuple data without modifying the original values.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next