Cơ BảnPython iconPython

`enumerate`, `zip`, `map`, `filter` — dùng khi nào?

Các built-ins quan trọng để xử lý collections hiệu quả:

python
# enumerate — loop có index
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

# zip — gộp nhiều iterables song song
names = ["Alice", "Bob"]
scores = [95, 87]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

# map — transform mỗi element (lazy)
doubled = list(map(lambda x: x * 2, [1, 2, 3]))  # [2, 4, 6]
# Prefer list comprehension: [x*2 for x in [1,2,3]]

# filter — lọc elements (lazy)
evens = list(filter(lambda x: x % 2 == 0, range(10)))
# Prefer: [x for x in range(10) if x % 2 == 0]

Pitfall: mapfilter trả về lazy iterators — cần list() để materialize.

Modern Python ưu tiên list comprehension hơn map/filter vì dễ đọc hơn.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python