Python List Methods Cheatsheet
A complete guide to Python list operations and methods.
List Methods
| Method | Description | Example |
|---|---|---|
append(x) |
Add to end | lst.append(5) |
extend(iterable) |
Add all items | lst.extend([1,2,3]) |
insert(i, x) |
Insert at index | lst.insert(0, "first") |
remove(x) |
Remove first occurrence | lst.remove(5) |
pop(i) |
Remove by index | lst.pop(-1) |
index(x) |
Find index | lst.index(5) |
count(x) |
Count occurrences | lst.count(5) |
sort() |
Sort in-place | lst.sort(reverse=True) |
reverse() |
Reverse in-place | lst.reverse() |
copy() |
Shallow copy | new = lst.copy() |
clear() |
Remove all | lst.clear() |
Code Examples
# List operations
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Sorting
sorted_nums = sorted(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
sorted_desc = sorted(numbers, reverse=True)
# List comprehension
squares = [x**2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
# Slicing
first_3 = numbers[:3] # [3, 1, 4]
last_3 = numbers[-3:] # [2, 6] (wait, let me recalculate)
reversed_lst = numbers[::-1]
# Useful functions
total = sum(numbers) # 31
maximum = max(numbers) # 9
minimum = min(numbers) # 1
unique = list(set(numbers)) # [1, 2, 3, 4, 5, 6, 9]
# Flattening nested lists
nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for sublist in nested for x in sublist]
# [1, 2, 3, 4, 5, 6]
# zip and enumerate
for i, val in enumerate(numbers[:3]):
print(f"Index {i}: {val}")
for a, b in zip([1,2,3], ["a","b","c"]):
print(f"{a}: {b}")
Follow me for more Python cheatsheets! 🐍
Follow for more Python content!
If you found this useful, you might like Python Automation Scripts Pack (10 Ready-to-Use Tools) — a practical resource that takes things a step further. At $14.99 it's a solid investment for your toolkit.
喜欢这篇文章?关注获取更多Python自动化内容!
Top comments (0)