Skip to content

Commit 5bbef29

Browse files
committed
Add tuples.py to demonstrate tuple operations and immutability in Python
1 parent a2af96f commit 5bbef29

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Tuples/tuples.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# ✅ Major difference between list and tuple: mutability
2+
# - Lists are mutable (can be modified)
3+
# - Tuples are immutable (cannot be modified)
4+
5+
tea_types = ("Black tea", "Green", "Oolong")
6+
print("Original tuple:", tea_types)
7+
print("First tea type:", tea_types[0])
8+
9+
# ❌ This line will cause a TypeError because tuples are immutable
10+
# tea_types[0] = "change" # Uncommenting this will raise: TypeError
11+
12+
# You can still find length
13+
print("Length of tuple:", len(tea_types))
14+
15+
# Tuples can be concatenated to make new tuples
16+
more_tea = ("Herbal", "Earl Grey")
17+
all_tea = more_tea + tea_types
18+
print("Concatenated tuple:", all_tea)
19+
20+
# Tuple type check
21+
print("Type of tea_types:", type(tea_types)) # <class 'tuple'>
22+
23+
# ✅ Additional add-ons:
24+
# ✅ Tuples can contain mixed data types
25+
mixed_tuple = ("Masala", 2, True)
26+
print("Mixed data tuple:", mixed_tuple)
27+
28+
# ✅ You can nest tuples
29+
nested_tuple = (("green", "black"), ("hot", "cold"))
30+
print("Nested tuple:", nested_tuple)
31+
32+
# ✅ You can iterate over a tuple just like a list
33+
for tea in tea_types:
34+
print("Tea variety:", tea)
35+
36+
# ✅ You can convert tuple -> list to modify it
37+
tea_list = list(tea_types)
38+
tea_list[0] = "Changed tea"
39+
print("Modified list version of tuple:", tea_list)
40+
41+
# ✅ Then convert back to tuple if needed
42+
tea_types = tuple(tea_list)
43+
print("Reconverted to tuple:", tea_types)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy