🔹 Common Python List Methods
| Method |
Definition |
Syntax |
Example |
Output |
| append() |
Adds an element to the end of the list |
list.append(element) |
lst = [1, 2]; lst.append(3) |
[1, 2, 3] |
| extend() |
Adds all elements of an iterable (list, tuple, etc.) |
list.extend(iterable) |
lst = [1, 2]; lst.extend([3, 4]) |
[1, 2, 3, 4] |
| insert() |
Inserts an element at a specific index |
list.insert(index, element) |
lst = [1, 3]; lst.insert(1, 2) |
[1, 2, 3] |
| remove() |
Removes the first occurrence of a value |
list.remove(value) |
lst = [1, 2, 3]; lst.remove(2) |
[1, 3] |
| pop() |
Removes and returns an element at a given index (default is last) |
list.pop(index) |
lst = [1, 2, 3]; lst.pop(1) |
2 (returns) & [1, 3] (list) |
🔹 Built-in Python Functions That Work on Lists
| Function |
Definition |
Syntax |
Example |
Output |
| len() |
Returns the length of the list |
len(list) |
len([1, 2, 3]) |
3 |
| sorted() |
Returns a new sorted list (doesn't modify original list) |
sorted(list, reverse=False) |
sorted([3, 1, 2]) |
[1, 2, 3] |
| max() |
Returns the largest element |
max(list) |
max([1, 5, 3]) |
5 |
| sum() |
Returns the sum of elements |
sum(list) |
sum([1, 2, 3]) |
6 |
🔥 Key Differences Between sort() and sorted()
| Feature |
sort() |
sorted() |
| Modifies original list? |
✅ Yes |
❌ No (returns a new list) |
| Returns a value? |
❌ No (returns None) |
✅ Yes (returns a new sorted list) |
| Usage |
list.sort() |
sorted(list) |
🔹 Additional Notes
- Mutability: All list methods that modify the list (
append, insert, remove, sort, reverse) change the original list and return None.
- List Comprehension Alternative: Many functions like
map(), filter(), and zip() can be replaced with list comprehensions for better readability.
Would you like more detailed examples for any of these methods? 🚀
Comments
Post a Comment