Python Basics — Day 11 Tuples & Sets in Python
Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey
Building skills in Python and full-stack development, with a focus on web apps and system design
Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering
From Python basics to full-stack projects, sharing my progress as I grow into a developer
Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development
01. Tuples
✅ Features
Store multiple values in order (similar to lists)
Use parentheses ( )
Immutable (cannot be changed) → good for read-only data
fruits = ("Apple", "Banana", "Grape")
print(fruits[0]) # Apple
print(fruits[-1]) # Grape
✅ Tuple vs List
list1 = [1, 2, 3] # List: mutable
tuple1 = (1, 2, 3) # Tuple: immutable
list1[0] = 100 # Allowed
# tuple1[0] = 100 # Error ❌
✅ Use Case
- Often used when returning multiple values from a function
def calc(a, b):
return a + b, a - b
result = calc(5, 2)
print(result) # (7, 3)
02. Sets
✅ Features
No duplicates, unordered
Use curly braces { }
Useful for mathematical set operations
nums = {1, 2, 3, 3, 4}
print(nums) # {1, 2, 3, 4} (duplicates removed)
✅ Common Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union {1, 2, 3, 4, 5}
print(a & b) # Intersection {3}
print(a - b) # Difference {1, 2}
print(a ^ b) # Symmetric difference {1, 2, 4, 5}
03. Set Methods
s = {1, 2, 3}
s.add(4) # Add element
s.remove(2) # Remove element
s.discard(5) # Remove element safely (no error if missing)
print(s)
s.clear() # Clear all elements
print(s) # set()
04. Casting Between Types
You can convert between lists, strings, sets, and tuples.
text = "banana"
print(set(text)) # {'b', 'a', 'n'} (duplicates removed)
numbers = [1, 2, 2, 3, 4]
unique = set(numbers)
print(list(unique)) # [1, 2, 3, 4]
05. Practice Examples
Example 1: Tuple
colors = ("red", "green", "blue")
for c in colors:
print(c)
Example 2: Set
my_set = {1, 2, 3}
my_set.add(2)
my_set.add(4)
print(my_set) # {1, 2, 3, 4}
Example 3: Remove Duplicates
nums = [1, 2, 2, 3, 3, 3, 4]
unique_nums = list(set(nums))
print(unique_nums) # [1, 2, 3, 4]