DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is Tuple in Python?

A Tuple in Python is a collection of elements that is ordered and immutable (we cannot change its elements after creation).

We create a tuple using round brackets ().

  1. Example of Tuple:

numbers = (10, 20, 30, 40, 50)
print(numbers)
print(numbers[0])
print(numbers[2])

Output:
(10, 20, 30, 40, 50)
10
30

Here:

  • numbers[0] returns 10.
  • numbers[2] returns 30.
  • Tuple supports indexing.
  1. Important Characteristics of Tuple:

  2. Ordered collection.

  3. Allows duplicate values.

  4. Immutable (cannot change elements).

  5. Supports indexing.

  6. Allows different data types.

  7. Faster for some operations than lists.

  8. Tuple Methods:

Python has two main built-in tuple methods:

  1. count() – Counts how many times an element appears. numbers = (10, 20, 10, 30, 10) print(numbers.count(10))

Output:
3

  1. index() – Returns the index of an element's first occurrence. numbers = (10, 20, 30, 40) print(numbers.index(30))

Output:
2

  1. Can we modify a Tuple?

No. We cannot directly add, remove, or update tuple elements.
numbers = (10, 20, 30)
numbers[0] = 100
print(numbers)

Output:
TypeError

Because tuples are immutable.

  1. Difference Between List, Tuple and Set:

Feature List Tuple Set
Symbols {}
Ordered Yes Yes No
Duplicates Yes Yes No
Mutable Yes No Yes
Indexing Yes Yes No

Top comments (0)