๐งพ Tuples in Python – Beginner-Friendly
One of the important data structures in Python is the tuple. In this article, we’ll explore what tuples are, how to use them, and why they’re useful.
✅ What is a Tuple?
A tuple is a collection of items that is:
-
Ordered: Items have a fixed position.
-
Immutable: You cannot change the items after the tuple is created.
-
Allows duplicates: You can have the same value more than once.
Think of a tuple like a list, but you can’t modify it after creation.
๐ How to Create a Tuple
Creating a tuple is easy! Just use parentheses ()
and separate the items with commas.
# A tuple with numbers
numbers = (1, 2, 3, 4)
# A tuple with mixed data types
person = ("Alice", 25, "Engineer")
# A tuple with one item (note the comma!)
single_item = (5,)
๐ Accessing Tuple Items
You can access tuple items by using their index, starting from 0.
person = ("Alice", 25, "Engineer")
print(person[0]) # Output: Alice
print(person[2]) # Output: Engineer
๐ซ Tuples are Immutable
Once a tuple is created, you cannot change it:
person = ("Alice", 25, "Engineer")
# This will give an error
# person[1] = 30
If you need a changeable version, consider using a list instead.
๐ Looping Through a Tuple
You can loop through a tuple using a for
loop:
colors = ("red", "green", "blue")
for color in colors:
print(color)
๐ง Tuple Methods
Even though tuples are immutable, they have a few useful methods:
-
.count(value)
– Returns the number of times a value appears. -
.index(value)
– Returns the index of the first occurrence of the value.
data = (1, 2, 3, 2, 4)
print(data.count(2)) # Output: 2
print(data.index(3)) # Output: 2
๐ฆ Tuple Packing and Unpacking
Packing means putting values into a tuple. Unpacking means assigning values from a tuple to variables.
# Packing
person = ("Bob", 30, "Doctor")
# Unpacking
name, age, job = person
print(name) # Bob
print(age) # 30
๐ When to Use a Tuple?
Use a tuple when:
-
You want to store a fixed collection of items.
-
You want to make sure the data cannot be changed.
-
You need to use the data as a key in a dictionary (tuples can be used as keys, but lists cannot).
✅ Quick Summary
Feature | Tuple | List |
---|---|---|
Mutable | ❌ No | ✅ Yes |
Ordered | ✅ Yes | ✅ Yes |
Allows Duplicates | ✅ Yes | ✅ Yes |
Syntax | (1, 2, 3) |
[1, 2, 3] |
๐ Example: Tuple in a Real Program
# List of students with their scores (name, score)
students = [
("Alice", 85),
("Bob", 78),
("Charlie", 92)
]
for name, score in students:
print(f"{name} scored {score} points.")
Watch video to understand tuple in python:
๐ฌ Final Thoughts
Tuples are a simple yet powerful feature in Python. Once you understand when and why to use them, they can help make your code cleaner, safer, and more efficient.
If you're new to Python, start by practicing with lists and tuples to get a good grip on how Python handles collections of data.
No comments:
Post a Comment