🐍 Understanding Python Tuples in Simple Way 📦


Python Tuple tutorial explaining tuple creation, indexing, immutability, nested tuples, and conversion to list with examples.

A Tuple is used to store multiple items in a single variable. It is a collection that is ordered, unchangeable, and allows duplicate values ✅.

📌 Creating a Tuple

sports = ("tennis", "cricket", "football")
print(len(sports))

len() function shows how many items are inside the tuple.

⚠ Single Item Tuple

To create a tuple with only one item, you must add a comma after the value.

tuple_1 = ("tennis",)

Without the comma, Python will treat it as a normal string.

📦 Different Data Types

Tuples can store different data types together.

my_tuple = ("tennis", 30, True)

🔢 Indexing in Tuple

Tuple items have index numbers starting from 0. You can also use negative indexing to access items from the end.

print(my_tuple[-1])  # Access last item

📚 Access Tuple Items (Range)

my_tuple = ("tennis", 30, "cricket", "football", True)

print(my_tuple[1:3])  # 30, cricket
print(my_tuple[:4])   # tennis, 30, cricket, football
print(my_tuple[2:])   # cricket, football, True

Range works the same way as lists. It starts from the first index and stops before the ending index.

✏ Update, Add, Remove Items

Tuples are unchangeable ❌. You cannot directly update, add, or remove items.

To modify a tuple:

  1. Convert tuple to list
  2. Change the list
  3. Convert back to tuple
my_tuple = ("tennis", 30, "cricket", "football", True)

y = list(my_tuple)
y[2] = "baseball"

my_tuple = tuple(y)
print(my_tuple)

📦 Nested Tuples

A Nested Tuple means a tuple inside another tuple.

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

print(nested_tuple[0][1])  # 2

Here, [0] selects the first inner tuple and [1] selects the second value inside it.

🎯 Tuples are useful when you want to store data that should not be changed. They are commonly used in Data Science and structured data storage 🚀.

📚 Related Articles

Article No Article Title & Link
1 🐍 Getting Started with Python for Data Science – Fundamentals Guide 🚀
2 🐍 Python Collections (Arrays) Simplified: List, Tuple, Set, & Dictionary 🐍
3 🐍 Understanding Python Lists in Simple Way 📋
4 🐍 Understanding Python Tuples in Simple Way 📦
5 🐍 Understanding Python Sets in Simple Way 🎴
6 🐍 Understanding Python Range & Dictionaries 📘
7 🐍Python Operators Guide: Arithmetic, Logical, & Precedence Explained 🐍
8 🐍 Python Control Statements Complete Guide 🔄
9 🐍 Python Functions Explained in Simple Way ⚙️
10 🐍 Python Map, Filter, Lambda & Modules – Simple Notes
11 🐍 Python OOP Concepts – Simple Short Notes
12 🐍  NumPy, Pandas & Web Scraping – Simple Python Notes📊

Post a Comment

Previous Post Next Post