Python_Lists_and_Sets_Guide
Python_Lists_and_Sets_Guide
1. Lists in Python
A list is an ordered, mutable (changeable) collection that can store different data types.
✨ Creating a List
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed = ['hello', 42, 3.14, True]
2. Sets in Python
A set is an unordered, immutable (unchangeable) collection that stores unique elements (no
duplicates).
✨ Creating a Set
numbers = {1, 2, 3, 4, 5}
fruits = {'apple', 'banana', 'cherry'}
🔹 Common Set Methods
| Method | Description & Example |
|--------|----------------------|
| add(x) | Adds x to the set. fruits.add('orange') |
| remove(x) | Removes x. fruits.remove('banana') |
| discard(x) | Removes x (No error if not found). fruits.discard('banana') |
| pop() | Removes a random element. fruits.pop() |
| clear() | Removes all elements. fruits.clear() |
| union(set2) | Combines sets. set1.union(set2) |
| intersection(set2) | Finds common elements. set1.intersection(set2) |
| difference(set2) | Finds products unique to set1. set1.difference(set2) |
| issubset(set2) | Checks if set1 is inside set2. set1.issubset(set2) |
| issuperset(set2) | Checks if set1 contains set2. set1.issuperset(set2) |
4. Summary
✅ Use Lists when order matters, and you need indexing or duplicate values.
✅ Use Sets when you need unique values and fast lookups (removing duplicates, set
operations).