Common Functions
Python offers a set of built-in functions that perform frequent operations such as counting, aggregation, sorting, and calculating minimum or maximum values. These functions are widely used in daily programming due to their simplicity and efficiency, and are part of the core of the language, so they do not require additional import.
Function | Description |
---|---|
len() | Returns the number of items in a sequence or iterable object. |
sum() | Returns the sum of all numeric elements of a sequence. |
max() | Returns the maximum value of a sequence. |
min() | Returns the minimum value. |
sorted() | Returns a new sorted list. |
abs() | Returns the absolute value of a number. |
round() | Rounds a decimal number to the nearest integer (or to a certain precision). |
pow() | Raises a number to a power (equivalent to **). |
divmod() | Returns a tuple with the quotient and remainder of a division. |
enumerate() | Returns an enumerated object (index and value) over an iterable. |
Below I will explain in more detail how these functions work:
Typical use: To count the number of elements in a sequence or collection.
names = ['Ana', 'Luis', 'Pedro']print(len(names))
Output:
3
Typical use: To calculate the total sum of the numeric elements of a sequence.
numbers = [10, 20, 30]print(sum(numbers))
Output:
60
Typical use: To get the highest value of a sequence.
ages = [15, 42, 37, 29]print(max(ages))
Output:
42
Typical use: To get the lowest value of a sequence.
temperatures = [23, 18, 30, 21]print(min(temperatures))
Output:
18
sorted()
Section titled “sorted()”Typical use: To sort the elements of a sequence and return a new sorted list.
letters = ['d', 'a', 'c', 'b']print(sorted(letters))
Output:
['a', 'b', 'c', 'd']
Typical use: To get the absolute value of a number.
number = -15print(abs(number))
Output:
15
round()
Section titled “round()”Typical use: To round a decimal number to the nearest integer.
pi = 3.14159print(round(pi, 2))
Output:
3.14
Typical use: To raise a base number to a power.
print(pow(2, 3)) # 2^3
Output:
8
divmod()
Section titled “divmod()”Typical use: To get the quotient and remainder of a division.
resultado = divmod(10, 3)print(resultado)
Output:
(3, 1)
enumerate()
Section titled “enumerate()”Typical use: Typical use: To iterate over a sequence obtaining index and value.
fruits = ['apple', 'banana', 'cherry']for index, value in enumerate(fruits): print(index, value)
Output:
0 manzana1 banana2 cereza