Command Palette

Search for a command to run...

Advanced Built-in Functions

Master powerful built-in functions like map, filter, reduce, zip, and more

map() Function

  • Applies a function to every item in an iterable
  • Returns a map object (iterator)
  • More concise than for loops
  • Can use with lambda functions
# Basic map usage
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))

# Map with regular function
def double(x):
    return x * 2

doubled = map(double, numbers)
print(list(doubled))

# Map with multiple iterables
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
sums = map(lambda x, y: x + y, nums1, nums2)
print(list(sums))

filter() Function

  • Filters items based on a condition
  • Returns only items where function returns True
  • Returns a filter object (iterator)
  • Useful for data cleaning and selection
# Basic filter usage
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))

# Filter with function
def is_positive(x):
    return x > 0

nums = [-2, -1, 0, 1, 2, 3]
positive = filter(is_positive, nums)
print(list(positive))

# Filter strings
words = ["apple", "banana", "cherry", "date"]
long_words = filter(lambda w: len(w) > 5, words)
print(list(long_words))

zip() and enumerate()

  • zip() combines multiple iterables into tuples
  • enumerate() adds counter to iterable
  • Both return iterators
  • Useful for parallel iteration
# zip() - combine lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = zip(names, ages)
print(list(combined))

# Unzip with zip and *
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
nums, letters = zip(*pairs)
print(nums, letters)

# enumerate() - add index
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# enumerate with custom start
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

Useful Built-in Functions

  • all() - returns True if all items are True
  • any() - returns True if any item is True
  • sorted() - returns sorted list
  • min(), max(), sum() - aggregate functions
# all() and any()
nums = [2, 4, 6, 8]
print(all(x % 2 == 0 for x in nums))  # True
print(any(x > 5 for x in nums))  # True

# sorted()
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(sorted(numbers))
print(sorted(numbers, reverse=True))

# Sort by key
words = ["banana", "pie", "apple", "cherry"]
print(sorted(words, key=len))

# min, max, sum
nums = [10, 20, 30, 40, 50]
print(f"Min: {min(nums)}")
print(f"Max: {max(nums)}")
print(f"Sum: {sum(nums)}")
print(f"Average: {sum(nums) / len(nums)}")