Understanding the most basic built-in functions in Python is essential for anyone beginning their journey in programming with this versatile and powerful language. Python is renowned for its simplicity and readability, and a significant part of this ease of use comes from its extensive standard library, which includes a multitude of built-in functions. These functions provide fundamental capabilities that allow programmers to perform common tasks without the need to write custom code for every operation. Below, let’s detail some of the most basic and frequently used built-in functions in Python, providing explanations and examples to illustrate their use.
1. `print()`
The `print()` function is one of the most fundamental functions in Python. It outputs data to the standard output device, usually the console. This function is indispensable for debugging and displaying information to the user.
Example:
python
print("Hello, World!")
print(42)
print(3.14)
print("The sum of 2 and 3 is", 2 + 3)
2. `len()`
The `len()` function returns the length (the number of items) of an object. The argument may be a sequence (such as a string, list, or tuple) or a collection (such as a dictionary).
Example:
python
print(len("Python")) # Output: 6
print(len([1, 2, 3, 4])) # Output: 4
print(len((1, 2, 3))) # Output: 3
print(len({"a": 1, "b": 2}))# Output: 2
3. `type()`
The `type()` function returns the type of an object. This can be useful for debugging and ensuring that variables are of the expected type.
Example:
python
print(type(42)) # Output: <class 'int'>
print(type(3.14)) # Output: <class 'float'>
print(type("Hello")) # Output: <class 'str'>
print(type([1, 2, 3])) # Output: <class 'list'>
4. `int()`, `float()`, `str()`
These functions are used to convert values to an integer, float, or string, respectively. They are essential for type conversion, which is a common requirement in many programming tasks.
Example:
python
print(int("42")) # Output: 42
print(float("3.14")) # Output: 3.14
print(str(42)) # Output: '42'
print(str(3.14)) # Output: '3.14'
5. `input()`
The `input()` function reads a line from input, converts it to a string, and returns it. This function is important for interactive programs that require user input.
Example:
python
name = input("Enter your name: ")
print("Hello, " + name + "!")
6. `sum()`
The `sum()` function takes an iterable (like a list or tuple) and returns the sum of its elements. This function is particularly useful for numerical computations.
Example:
python print(sum([1, 2, 3, 4])) # Output: 10 print(sum((1, 2, 3, 4))) # Output: 10
7. `min()` and `max()`
The `min()` and `max()` functions return the smallest and largest item in an iterable, respectively. They can also take multiple arguments and return the smallest or largest among them.
Example:
python print(min(3, 1, 4, 1, 5)) # Output: 1 print(max(3, 1, 4, 1, 5)) # Output: 5 print(min([3, 1, 4, 1, 5])) # Output: 1 print(max([3, 1, 4, 1, 5])) # Output: 5
8. `sorted()`
The `sorted()` function returns a new sorted list from the elements of any iterable. It is a highly versatile function that can sort data in ascending or descending order.
Example:
python print(sorted([3, 1, 4, 1, 5])) # Output: [1, 1, 3, 4, 5] print(sorted([3, 1, 4, 1, 5], reverse=True)) # Output: [5, 4, 3, 1, 1]
9. `range()`
The `range()` function generates a sequence of numbers, which is often used in for-loops. It can take one, two, or three arguments.
Example:
python print(list(range(5))) # Output: [0, 1, 2, 3, 4] print(list(range(1, 6))) # Output: [1, 2, 3, 4, 5] print(list(range(1, 10, 2)))# Output: [1, 3, 5, 7, 9]
10. `enumerate()`
The `enumerate()` function adds a counter to an iterable and returns it as an enumerate object. This is particularly useful for obtaining an index along with the value when iterating over a list.
Example:
python
for index, value in enumerate(["a", "b", "c"]):
print(index, value)
# Output:
# 0 a
# 1 b
# 2 c
11. `zip()`
The `zip()` function takes iterables (can be zero or more), aggregates them in a tuple, and returns it. This is useful for iterating over multiple sequences in parallel.
Example:
python
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(name, score)
# Output:
# Alice 85
# Bob 90
# Charlie 95
12. `map()`
The `map()` function applies a given function to all items in an input list (or any iterable) and returns a list of the results. It is a powerful tool for functional programming.
Example:
python
def square(x):
return x * x
print(list(map(square, [1, 2, 3, 4]))) # Output: [1, 4, 9, 16]
13. `filter()`
The `filter()` function constructs an iterator from elements of an iterable for which a function returns true. This is useful for extracting elements that meet certain criteria.
Example:
python
def is_even(x):
return x % 2 == 0
print(list(filter(is_even, [1, 2, 3, 4])))# Output: [2, 4]
14. `reduce()`
The `reduce()` function, which is part of the `functools` module, applies a rolling computation to sequential pairs of values in a list. This is useful for cumulative operations like summing or multiplying all elements.
Example:
python
from functools import reduce
def add(x, y):
return x + y
print(reduce(add, [1, 2, 3, 4])) # Output: 10
15. `any()` and `all()`
The `any()` function returns `True` if any element of the iterable is true. If the iterable is empty, it returns `False`. Conversely, the `all()` function returns `True` if all elements of the iterable are true (or if the iterable is empty).
Example:
python print(any([False, True, False])) # Output: True print(all([False, True, False])) # Output: False print(any([False, False, False])) # Output: False print(all([True, True, True])) # Output: True
16. `chr()` and `ord()`
The `chr()` function returns the string representing a character whose Unicode code point is the integer passed as an argument. The `ord()` function returns an integer representing the Unicode code point of a given Unicode character.
Example:
python
print(chr(97)) # Output: 'a'
print(ord('a')) # Output: 97
17. `abs()`
The `abs()` function returns the absolute value of a number. This is a fundamental mathematical function used in various computations.
Example:
python print(abs(-5)) # Output: 5 print(abs(3.14)) # Output: 3.14
18. `round()`
The `round()` function returns a floating-point number rounded to the specified number of decimals. If no number of decimals is specified, it rounds to the nearest integer.
Example:
python print(round(3.14159, 2)) # Output: 3.14 print(round(3.14159)) # Output: 3
19. `divmod()`
The `divmod()` function takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.
Example:
python print(divmod(9, 4)) # Output: (2, 1)
20. `pow()`
The `pow()` function returns the value of x raised to the power of y. If a third argument is provided, it returns x raised to the power of y, modulo z.
Example:
python print(pow(2, 3)) # Output: 8 print(pow(2, 3, 5)) # Output: 3
21. `isinstance()`
The `isinstance()` function checks if an object is an instance or subclass of a class or a tuple of classes.
Example:
python
print(isinstance(42, int)) # Output: True
print(isinstance(42, str)) # Output: False
print(isinstance("Hello", (int, str))) # Output: True
22. `issubclass()`
The `issubclass()` function checks if a class is a subclass of another class or a tuple of classes.
Example:
python
class A:
pass
class B(A):
pass
print(issubclass(B, A)) # Output: True
print(issubclass(A, B)) # Output: False
23. `help()`
The `help()` function invokes the built-in help system. It is highly useful for obtaining documentation on modules, classes, functions, and keywords.
Example:
python help(print)
24. `dir()`
The `dir()` function attempts to return a list of valid attributes of the object. If the object is a module, it returns the list of names defined in the module.
Example:
python print(dir([])) # Output: List of attributes and methods of a list object print(dir(str)) # Output: List of attributes and methods of a string object
25. `eval()`
The `eval()` function parses the expression passed to it and runs Python expression (code) within the program.
Example:
python
x = 1
print(eval('x + 1')) # Output: 2
26. `exec()`
The `exec()` function executes the dynamically created program, which is either a string or a code object.
Example:
python
exec('x = 5')
print(x) # Output: 5
27. `globals()` and `locals()`
The `globals()` function returns a dictionary representing the current global symbol table. The `locals()` function returns a dictionary representing the current local symbol table.
Example:
python print(globals()) print(locals())
28. `id()`
The `id()` function returns the identity of an object. This identity is unique and constant for this object during its lifetime.
Example:
python a = 42 print(id(a)) # Output: Some unique identifier
29. `hash()`
The `hash()` function returns the hash value of an object (if it has one). Hash values are integers used to quickly compare dictionary keys during a dictionary lookup.
Example:
python
print(hash("Hello")) # Output: Some integer hash value
30. `memoryview()`
The `memoryview()` function returns a memory view object of the given argument. A memory view object exposes the buffer interface to Python objects.
Example:
python
b = bytearray('XYZ', 'utf-8')
m = memoryview(b)
print(m[0]) # Output: 88 (ASCII value of 'X')
31. `open()`
The `open()` function opens a file and returns a corresponding file object. It is essential for file handling in Python.
Example:
python
f = open('example.txt', 'r')
print(f.read())
f.close()
32. `repr()`
The `repr()` function returns a string representation of an object that can be used to recreate the object using `eval()`.
Example:
python
print(repr("Hello, World!")) # Output: "'Hello, World!'"
33. `set()`
The `set()` function returns a new set object, optionally with elements taken from an iterable.
Example:
python
print(set([1, 2, 3, 2, 1])) # Output: {1, 2, 3}
34. `frozenset()`
The `frozenset()` function returns a new frozenset object, optionally with elements taken from an iterable. A frozenset is an immutable version of a set.
Example:
python
print(frozenset([1, 2, 3, 2, 1])) # Output: frozenset({1, 2, 3})
35. `slice()`
The `slice()` function returns a slice object representing the set of indices specified by range(start, stop, step).
Example:
python s = slice(1, 5, 2) print([0, 1, 2, 3, 4, 5][s]) # Output: [1, 3]
36. `staticmethod()`
The `staticmethod()` function returns a static method for a function. It is used inside a class to define methods that do not operate on an instance or class.
Example:
python
class MyClass:
@staticmethod
def static_method():
print("This is a static method.")
MyClass.static_method() # Output: This is a static method.
37. `property()`
The `property()` function returns a property attribute. It is used to manage the access to instance attributes.
Example:
python
class MyClass:
def __init__(self):
self._x = None
def get_x(self):
return self._x
def set_x(self, value):
self._x = value
def del_x(self):
del self._x
x = property(get_x, set_x, del_x, "I'm the 'x' property.")
obj = MyClass()
obj.x = 42
print(obj.x) # Output: 42
38. `super()`
The `super()` function returns a proxy object that delegates method calls to a parent or sibling class of type. It is used to call a method from the parent class.
Example:
python
class Parent:
def __init__(self):
self.value = "Parent"
class Child(Parent):
def __init__(self):
super().__init__()
self.value = "Child"
obj = Child()
print(obj.value) # Output: Child
39. `vars()`
The `vars()` function returns the `__dict__` attribute of the given object. If no argument is provided, it acts like `locals()`.
Example:
python
class MyClass:
def __init__(self):
self.a = 1
self.b = 2
obj = MyClass()
print(vars(obj)) # Output: {'a': 1, 'b': 2}
40. `__import__()`
The `__import__()` function is called by the `import` statement. It can be used to import a module programmatically.
Example:
python
math = __import__('math')
print(math.sqrt(16)) # Output: 4.0
These built-in functions provide a solid foundation for working with Python. They cover a wide range of functionalities, from basic input/output to more advanced operations like type conversion, mathematical computations, and object introspection. Familiarity with these functions will greatly enhance one’s ability to write efficient and effective Python code.
Other recent questions and answers regarding Built-in functions:
- Why is it important to understand slices when analyzing game boards in Python?
- What is the advantage of using indexing in Python?
- What is the symbol used to add comments in Python code?
- How can we iterate over a list of lists using a "for" loop in Python?
- What is the purpose of using the "enumerate" function in Python?
More questions and answers:
- Field: Computer Programming
- Programme: EITC/CP/PPF Python Programming Fundamentals (go to the certification programme)
- Lesson: Functions (go to related lesson)
- Topic: Built-in functions (go to related topic)

