Tuples in Python
✅ What is a Tuple?
A tuple is a collection in Python that lets you store multiple items in a single variable.
It is:
- Ordered – items stay in the same order
- Immutable – you cannot change the items once added
- Allows duplicates – repeated values are okay
๐จ How to Create a Tuple
Use round brackets () to create a tuple.
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)
๐ You can also create a tuple without parentheses (Python understands it):
my_tuple = "apple", "banana", "cherry"
๐งช Tuple Examples
fruits = ("apple", "banana", "cherry")
numbers = (1, 2, 3, 4)
mixed = (1, "hello", 3.5)
✅ Tuples can contain:
- Strings
- Integers
- Floats
- Booleans
- Other tuples!
๐ข Accessing Tuple Items
Use index numbers to access values (starting from 0):
colors = ("red", "blue", "green")
print(colors[0]) # red
print(colors[1]) # blue
You can also use negative indexing:
print(colors[-1]) # green (last item)
๐ซ Tuples are Immutable
Once a tuple is created, you can't change, add, or remove items:
numbers = (1, 2, 3)
# numbers[0] = 10 ❌ This will give an error
๐ Tuple Length
Use the len() function:
my_tuple = ("a", "b", "c")
print(len(my_tuple)) # 3
๐ Looping Through a Tuple
Use a for loop to go through items:
colors = ("red", "blue", "green")
for color in colors:
print(color)
๐ Tuple Operations
✅ Concatenation:
t1 = (1, 2)
t2 = (3, 4)
result = t1 + t2 # (1, 2, 3, 4)
✅ Repetition:
t = ("hi",)
print(t * 3) # ('hi', 'hi', 'hi')
๐ Checking for an Item
fruits = ("apple", "banana", "cherry")
if "apple" in fruits:
print("Yes, apple is there!")
๐งฉ Tuple with One Item?
You must add a comma if the tuple has only one item:
t = ("hello",) # This is a tuple
x = ("hello") # This is just a string
๐งฑ Nesting Tuples
Tuples can contain other tuples:
nested = (1, 2, (3, 4))
๐ฆ Tuple Packing and Unpacking
Packing:
info = ("Ansh", 7, "India")
Unpacking:
name, age, country = info
print(name) # Ansh
print(age) # 7
print(country) # India
๐ Converting Lists to Tuples
Use the tuple() function:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3)
๐ Tuple Methods
| Method | Description |
|---|---|
| count() | Counts how many times an item appears |
| index() | Returns the index of the first occurrence of an item |
Example:
t = (1, 2, 3, 2, 4)
print(t.count(2)) # 2
print(t.index(3)) # 2
✅ When to Use Tuples?
Use tuples when:
- You want data to be unchanged (read-only)
- You are storing a fixed set of items
- You want faster access than a list
๐ Summary
- Tuples use
()to store multiple items - They are ordered and immutable
- You can access items with indexing
- Tuples are faster and safer than lists for fixed data
- You can loop, count, and unpack tuples
No comments:
Post a Comment