Python Tuples Explained for Beginners (With Simple Examples)

Python Tuples Explained for Beginners (With Simple Examples)

Python Tuples Explained for Beginners (With Simple Examples)

Introduction

In the previous post, we learned about Python Lists. Now let’s learn another important data structure in Python called Tuple.

Tuples are very similar to lists, but with one major difference — they cannot be changed.

---

What is a Tuple?

A tuple is a collection of items that is:

  • Ordered
  • Immutable (cannot be modified)
  • Allows duplicate values
Once a tuple is created, you cannot add, remove, or change its elements.
---

How to Create a Tuple

Tuples are created using round brackets ( ).

numbers = (10, 20, 30)
print(numbers)
---

Tuple with Different Data Types

A tuple can store multiple data types together.

data = ("Ayush", 22, True, 75.5)
print(data)
---

Accessing Tuple Elements

You can access tuple elements using index numbers.

colors = ("red", "green", "blue")

print(colors[0])
print(colors[2])
Indexing starts from 0, just like lists.
---

Negative Indexing

Python also supports negative indexing.

colors = ("red", "green", "blue")
print(colors[-1])
---

Why Tuples are Immutable

Let’s try to change a tuple value.

numbers = (1, 2, 3)
numbers[0] = 10
❌ This will cause an error because tuples cannot be modified.
---

Tuple vs List (Important Difference)

  • List → Mutable (can be changed)
  • Tuple → Immutable (cannot be changed)
# List
my_list = [1, 2, 3]
my_list[0] = 10

# Tuple
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  ❌ Error
---

Tuple Length

Use len() to find the number of elements.

fruits = ("apple", "banana", "cherry")
print(len(fruits))
---

Looping Through a Tuple

You can use a for loop to iterate over a tuple.

fruits = ("apple", "banana", "cherry")

for fruit in fruits:
    print(fruit)
---

When Should You Use Tuples?

  • When data should not change
  • To protect data from modification
  • Faster than lists
---

What You Learned in This Post

  • What is a tuple
  • How to create tuples
  • Accessing tuple elements
  • Difference between list and tuple
---

What’s Next?

Now that you understand tuples, the next data structure is Sets.

Next Post: Python Sets Explained for Beginners

---

👋 About the Author

Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast

📧 Email: aygupta9898@gmail.com

Comments

Popular posts from this blog

What is Programming? Simple Explanation for Beginners

What is Python? Why Learn Python for Beginners

How to Install Python on Windows and Mac (Step-by-Step Guide)