Notes
Categories

Tuple in Python [ English ]

< Prev Next >

1. Introduction

A tuple in Python is a collection of items stored in a single variable, similar to a list. However, the key difference is:

Tuples are immutable (cannot be changed after creation)


2. Characteristics of Tuple


3. Creating a Tuple

Syntax

tuple_name = (elements)

Example

numbers = (1, 2, 3)
names = ("Amit", "Rahul", "Priya")
mixed = (10, "Python", 3.5)

Single Element Tuple

t = (5,)

👉 Comma is required, otherwise it is not considered a tuple.


4. Accessing Elements

Indexing

numbers = (10, 20, 30)

print(numbers[0])
print(numbers[1])

Output

10
20

Negative Indexing

print(numbers[-1])

Output

30

5. Slicing a Tuple

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

print(numbers[1:4])

Output

(2, 3, 4)

6. Immutability of Tuple

numbers = (1, 2, 3)

numbers[1] = 10   # Error

Explanation


7. Tuple Operations

Concatenation

a = (1, 2)
b = (3, 4)

print(a + b)

Repetition

print((1, 2) * 2)

Membership

print(2 in (1, 2, 3))

8. Looping Through a Tuple

numbers = (1, 2, 3)

for n in numbers:
    print(n)

9. Tuple Packing and Unpacking

Packing

t = 1, 2, 3

Unpacking

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

print(a, b, c)

10. Nested Tuple

t = ((1, 2), (3, 4))

print(t[0][1])

Output

2

11. Built-in Functions for Tuple

Function Description
len() Returns number of elements
max() Returns maximum value
min() Returns minimum value
sum() Returns sum of elements

12. Difference Between List and Tuple

Feature List Tuple
Mutability Mutable Immutable
Syntax [ ] ( )
Performance Slower Faster
Usage Changeable data Fixed data

13. Advantages of Tuple


14. Summary

< Prev Next >