Python Built-in Functions
1. abs(): Returns the absolute value of a number.
print(abs(-5)) # Output: 5
2. all(): Returns True if all elements in an iterable are true.
print(all([True, True, False])) # Output: False
3. any(): Returns True if any element in an iterable is true.
print(any([False, False, True])) # Output: True
4. ascii(): Returns a string containing a printable representation of an object, but escapes
non-ASCII characters.
print(ascii('Hello, world!')) # Output: 'Hello, world!'
print(ascii('你好')) # Output: '\u4f60\u597d'
5. bin(): Converts an integer to a binary string.
print(bin(10)) # Output: '0b1010'
6. bool(): Converts a value to a Boolean, using the standard truth testing procedure.
print(bool(0)) # Output: False
print(bool(1)) # Output: True
7. bytearray(): Returns a new array of bytes.
b = bytearray([1, 2, 3])
print(b) # Output: bytearray(b'\x01\x02\x03')
8. bytes(): Returns a new 'bytes' object, which is an immutable sequence of bytes.
b = bytes([1, 2, 3])
print(b) # Output: b'\x01\x02\x03'
9. callable(): Returns True if the object appears callable, False otherwise.
def foo():
pass
print(callable(foo)) # Output: True
print(callable(42)) # Output: False
10. chr(): Returns the string representing a character whose Unicode code point is the
integer.
print(chr(97)) # Output: 'a'
11. classmethod(): Transforms a method into a class method.
class MyClass:
@classmethod
def my_classmethod(cls):
print('class method called')
MyClass.my_classmethod() # Output: class method called
12. compile(): Compiles source into a code or AST object.
code = compile('print("Hello, world!")', '<string>', 'exec')
exec(code) # Output: Hello, world!
13. complex(): Creates a complex number.
z = complex(1, 2)
print(z) # Output: (1+2j)
14. delattr(): Deletes an attribute from an object.
class MyClass:
pass
obj = MyClass()
obj.attr = 10
delattr(obj, 'attr')
15. dict(): Creates a new dictionary.
d = dict(a=1, b=2)
print(d) # Output: {'a': 1, 'b': 2}
16. dir(): Attempts to return a list of valid attributes for the object.
print(dir([])) # Output: List of attributes and methods of a list
17. divmod(): Takes two numbers and returns a pair of numbers (a tuple) consisting of their
quotient and remainder.
print(divmod(9, 4)) # Output: (2, 1)