jkrPython Lists & Sets – Beginner 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]
🔹 Common List Methods
| Method | Description & Example |
|--------|----------------------|
| append(x) | Adds x to the end. fruits.append('orange') |
| insert(i, x) | Inserts x at index i. fruits.insert(1, 'grape') |
| extend(iterable) | Adds multiple items. fruits.extend(['kiwi', 'mango']) |
| remove(x) | Removes first occurrence of x. fruits.remove('banana') |
| pop(i) | Removes and returns element at index i (default last). fruits.pop(2) |
| index(x) | Returns index of x. fruits.index('cherry') |
| count(x) | Counts occurrences of x. fruits.count('apple') |
| reverse() | Reverses the list. fruits.reverse() |
| clear() | Removes all elements. fruits.clear() |
| len(list) | Returns number of elements. len(fruits) |
🔹 Example: Using List Methods
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange') # ['apple', 'banana', 'cherry', 'orange']
fruits.insert(1, 'grape') # ['apple', 'grape', 'banana', 'cherry', 'orange']
fruits.pop() # Removes 'orange'
print(fruits) # ['apple', 'grape', 'banana', 'cherry']
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) |
🔹 Example: Using Set Methods
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.add(6) # {1, 2, 3, 4, 5, 6}
set1.remove(2) # {1, 3, 4, 5, 6}
common = set1.intersection(set2) # {4, 5, 6}
all_items = set1.union(set2) # {1, 3, 4, 5, 6, 7, 8}
print(common, all_items)
3. Lists vs. Sets – Key Differences
| Feature | Lists | Sets |
|---------|-------|------|
| Order | Ordered | Unordered |
| Duplicates | Allowed | Not allowed |
| Indexing | Yes | No |
| Mutable | Yes | Yes (but unordered) |
| Common Uses | Storing data in sequence | Removing duplicates, mathematical operations |
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).