More Built-in Functions
Python provides many built-in functions that are useful when working with collections and other data types. This section covers some of the most commonly used built-in functions.
any()
The any() function returns True if any element of the iterable is truthy, otherwise it returns False.
print(any([0, 1, 2])) # True (at least one element is truthy)print(any([0, 0, 0])) # False (no truthy elements)print(any([])) # False (empty iterable)print(any([False, None, ""])) # False (all falsy)print(any((False, 0, "hello"))) # True (at least one truthy)print(any("")) # False (empty string)print(any({0: "a", 1: "b"})) # True (has truthy keys)print(any({0, False, None})) # False (all falsy)Note
If the iterable is empty,
any()returnsFalse.
all()
The all() function returns True if all elements of the iterable are truthy, otherwise it returns False.
print(all([1, 2, 3])) # True (all elements are truthy)print(all([1, 2, 0])) # False (0 is falsy)print(all([])) # True (empty iterable)print(all([True, 1, "hello"])) # True (all truthy)print(all((True, 0, "hello"))) # False (0 is falsy)print(all("hello")) # True (all characters are truthy)print(all("")) # True (empty string)print(all({0: "a", 1: "b"})) # False (0 is falsy)print(all({1, 2, 3})) # True (all elements are truthy)Note
If the iterable is empty,
all()returnsTrue.
hash()
The hash() function returns the hash value of an object. Hash values are integers used to quickly compare dictionary keys and set elements.
print(hash("hello")) # Some integer valueprint(hash(42)) # 42 (integers hash to themselves)print(hash((1, 2, 3))) # Some integer valueMutable objects are not hashable:
# This will raise a TypeError# hash([1, 2, 3]) # TypeError: unhashable type: 'list'# hash({1, 2, 3}) # TypeError: unhashable type: 'set'# hash({"a": 1}) # TypeError: unhashable type: 'dict'Two objects that are equal must have the same hash value:
Warning
The hash value of an object may change between different Python runs. Do not rely on hash values being consistent across program executions.
divmod()
The divmod() function takes two numbers and returns a tuple containing the quotient and remainder of the division.
result = divmod(10, 3)print(result) # (3, 1)print(result[0]) # 3 (quotient)print(result[1]) # 1 (remainder)
# Equivalent to:quotient, remainder = divmod(10, 3)print(quotient) # 3print(remainder) # 1divmod() is equivalent to (a // b, a % b):
bin()
The bin() function converts an integer to a binary string prefixed with "0b".
print(bin(10)) # 0b1010print(bin(0)) # 0b0print(bin(255)) # 0b11111111print(bin(-10)) # -0b1010oct()
The oct() function converts an integer to an octal string prefixed with "0o".
print(oct(10)) # 0o12print(oct(0)) # 0o0print(oct(64)) # 0o100print(oct(-10)) # -0o12hex()
The hex() function converts an integer to a lowercase hexadecimal string prefixed with "0x".
print(hex(10)) # 0xaprint(hex(0)) # 0x0print(hex(255)) # 0xffprint(hex(16)) # 0x10print(hex(-10)) # -0xazip()
The zip() function takes multiple iterables and returns an iterator of tuples, where each tuple contains the elements from each iterable at the same position.
list1 = [1, 2, 3]list2 = ['a', 'b', 'c']result = zip(list1, list2)print(list(result)) # [(1, 'a'), (2, 'b'), (3, 'c')]zip() stops when the shortest iterable is exhausted:
list1 = [1, 2, 3, 4]list2 = ['a', 'b']result = zip(list1, list2)print(list(result)) # [(1, 'a'), (2, 'b')] - stops at shortestYou can zip more than two iterables:
numbers = [1, 2, 3]letters = ['a', 'b', 'c']symbols = ['!', '@', '#']result = zip(numbers, letters, symbols)print(list(result)) # [(1, 'a', '!'), (2, 'b', '@'), (3, 'c', '#')]enumerate()
The enumerate() function adds a counter to an iterable and returns an enumerate object that generates pairs of (index, value).
fruits = ['apple', 'banana', 'cherry']result = enumerate(fruits)print(list(result)) # [(0, 'apple'), (1, 'banana'), (2, 'cherry')]A starting index can be specified:
fruits = ['apple', 'banana', 'cherry']result = enumerate(fruits, start=1)print(list(result)) # [(1, 'apple'), (2, 'banana'), (3, 'cherry')]A common use case is getting both the index and value when looping:
fruits = ['apple', 'banana', 'cherry']for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")# Output:# 0: apple# 1: banana# 2: cherryWithout enumerate(), you would need to use range() and indexing:
fruits = ['apple', 'banana', 'cherry']for i in range(len(fruits)): print(f"{i}: {fruits[i]}")reversed()
The reversed() function returns a reverse iterator that iterates over the elements of a sequence in reverse order.
numbers = [1, 2, 3, 4, 5]reversed_numbers = reversed(numbers)print(list(reversed_numbers)) # [5, 4, 3, 2, 1]print(numbers) # [1, 2, 3, 4, 5] (original unchanged)reversed() works with any sequence type:
# With tuplest = (1, 2, 3, 4, 5)reversed_t = reversed(t)print(list(reversed_t)) # [5, 4, 3, 2, 1]
# With stringss = "hello"reversed_s = reversed(s)print(list(reversed_s)) # ['o', 'l', 'l', 'e', 'h']print("".join(reversed_s)) # 'olleh' (but iterator is exhausted)print("".join(reversed("hello"))) # 'olleh'reversed() returns an iterator, so it needs to be converted to a list or used in a loop:
numbers = [1, 2, 3, 4, 5]for num in reversed(numbers): print(num)# Output:# 5# 4# 3# 2# 1Note
For lists, you can also use the
.reverse()method, but it modifies the list in place and returnsNone. Thereversed()function returns a new iterator without modifying the original sequence.
slice()
The slice() function returns a slice object that can be used for slicing sequences. It’s equivalent to using the slice notation [start:stop:step].
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]s = slice(2, 7, 2)print(numbers[s]) # [2, 4, 6]# Equivalent to: numbers[2:7:2]Creating slice objects:
# slice(stop)s1 = slice(5)print(s1) # slice(None, 5, None)
# slice(start, stop)s2 = slice(2, 7)print(s2) # slice(2, 7, None)
# slice(start, stop, step)s3 = slice(2, 10, 2)print(s3) # slice(2, 10, 2)Using slice objects:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# First 5 elementss = slice(5)print(numbers[s]) # [0, 1, 2, 3, 4]
# Elements from index 2 to 7s = slice(2, 7)print(numbers[s]) # [2, 3, 4, 5, 6]
# Every 2nd element from index 2 to 10s = slice(2, 10, 2)print(numbers[s]) # [2, 4, 6, 8]Slice objects can be stored and reused:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]first_half = slice(0, 5)second_half = slice(5, 10)
print(numbers[first_half]) # [0, 1, 2, 3, 4]print(numbers[second_half]) # [5, 6, 7, 8, 9]
# Works with strings tootext = "Hello, World!"print(text[first_half]) # "Hello"print(text[second_half]) # ", World!"Slice objects have attributes:
s = slice(2, 10, 2)print(s.start) # 2print(s.stop) # 10print(s.step) # 2