📘 Day 2: Lists, Tuples, Sets & Dictionaries in Python
🔹 1. Lists
- Lists are ordered, mutable, and allow duplicate values.
- Defined using square brackets
[]
.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry', 'orange']
✅ Common Methods: append()
, insert()
, remove()
, pop()
, sort()
, reverse()
🔹 2. Tuples
- Tuples are ordered, immutable, and allow duplicates.
- Defined using parentheses
()
.
coordinates = (10, 20)
print(coordinates[0]) # 10
# coordinates[0] = 30 ❌ Error!
✅ Used when values should not change, e.g., GPS coordinates.
🔹 3. Sets
- Sets are unordered, mutable, and do not allow duplicates.
- Defined using curly braces
{}
or set()
function.
unique_numbers = {1, 2, 3, 2, 4}
print(unique_numbers) # {1, 2, 3, 4}
✅ Common Uses: Removing duplicates, set operations (union, intersection, difference)
🔹 4. Dictionaries
- Dictionaries are unordered (insertion ordered as of Python 3.6+), mutable, and store key-value pairs.
- Defined using curly braces
{key: value}
.
person = {"name": "Alice", "age": 25}
person["city"] = "New York"
print(person["name"]) # Alice
✅ Access with keys, not indexes.
📌 Summary Table
Data Type | Ordered | Mutable | Allows Duplicates | Syntax |
List | ✅ | ✅ | ✅ | [] |
Tuple | ✅ | ❌ | ✅ | () |
Set | ❌ | ✅ | ❌ | {} |
Dictionary | ✅* | ✅ | ❌ (keys) | {key:val} |
💡 Interview Tips
- Prefer tuples when values shouldn't change.
- Use sets to remove duplicates.
- Dictionaries are ideal for key-based lookups.
- Understand list vs set performance in search operations.
🔍 Practice Questions
- List vs Tuple: When and why?
- How to convert a list to set and vice versa?
- How to merge two dictionaries?
- Use case of tuple in real-world apps?