What are Python's built-in math and utility functions?
· Category: Python Programming
Short answer
Python includes many built-in functions for common tasks. len() returns the length of a collection, range() generates sequences of numbers, enumerate() adds indices, zip() pairs iterables, and map()/filter() apply transformations and predicates.
How it works
# len
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
# range
print(list(range(3))) # [0, 1, 2]
print(list(range(1, 6, 2))) # [1, 3, 5]
# enumerate
for idx, val in enumerate(["a", "b"]):
print(idx, val)
# zip
keys = ["x", "y"]
vals = [10, 20]
print(dict(zip(keys, vals))) # {'x': 10, 'y': 20}
Example
Using map() and filter():
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(squared) # [1, 4, 9, 16, 25]
print(evens) # [2, 4]
Why it matters
Built-in functions are implemented in C and are highly optimized. Using them instead of manual loops makes code shorter, faster, and more Pythonic.
Common issues
map()andfilter()return iterators in Python 3; wrap them inlist()if you need a list.zip()stops at the shortest input; useitertools.zip_longest()to pad shorter iterables.len()does not work on iterators because they do not support random access.