Python’s Top 29 Built-In Functions with Examples

Python’s Top 29 Built-In Functions with Examples

https://ift.tt/3vqzfsw

Python comes with many built-in functions you can use without importing a library. There are 64 of them. In this article, you’ll get an overview of the most important ones.

Let’s dive into the most important 29 Python built-in functions next!

help()

Python’s built-in help() function launches Python’s help system. Without an argument, help() starts an interactive session. With a string argument, help(name) looks up the name and prints a help page to the shell. With a non-string argument, help(object) prints a help page on object.

>>> help(list)             # Prints the documentation of list
>>> help(dict)             # Prints the documentation of dict
>>> help(int)              # Prints the documentation of int
>>> help('help')           # Prints the documentation of help()
>>> help()                 # Opens an interactive "help" session

input()

Python’s built-in input() function reads a string from the standard input. The function blocks until such input becomes available and the user hits ENTER. You can add an optional prompt string as an argument to print a custom string to the standard output without a trailing newline character to tell the user that your program expects their input.

>>> s = input()
42
>>> s
'42'

print()

Python’s built-in print() function prints a string representation of any number of objects to the standard output. The print() function has many advanced arguments to customize the behavior—such as the separator argument to set a custom separator string between the printed objects, the end argument to set a custom ending string, or the file argument that even allows you to print a string into a file object.

>>> print('hello')
hello
>>> print('hello world')
hello world
>>> print(42)
42
>>> print(1, 2, 3)
1 2 3
>>> print('hello', 'world', sep = '\n')
hello
world
>>> print('hello', 'world', sep = '\n', end = '\n-----\n')
hello
world
-----

format()

Python’s built-in format(value, spec) function transforms input of one format into output of another format defined by you. Specifically, it applies the format specifier spec to the argument value and returns a formatted representation of value. For example, format(42, 'f') returns the string representation '42.000000'.

>>> format(42)
'42'
>>> format(42, 'f')
'42.000000'
>>> format(42, '.10f')
'42.0000000000'
>>> format(42, '.2f')
'42.00'

exec()

Python’s exec() function executes the Python code you pass as a string or executable object argument. This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime. This way, you can run programmatically-created Python code.

>>> program = 'print("hello world")'
>>> exec(program)
hello world
>>> exec('x=2; y=4; print(x+y)')
6

Every Python master understands the basics very well. Python built-in functions are the very foundation your whole coding career stands on. For a full course on all 64 Python built-in functions, check out the Finxter Computer Science Academy:

eval()

Python eval(s) parses the string argument s into a Python expression, runs it, and returns the result of the expression. This poses a security risk because a user can use it to run code on your computer. For example, if you allow eval(input()), a user could type os.system('rm -R *') to delete all files in your home directory.

>>> eval('2+2')
4
>>> eval('[1, 2, 3]*3')
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> eval('[x for x in range(10)]')
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> eval('"Alice".replace("e", "")')
'Alic'

compile()

Python’s built-in compile() method returns an executable code object as an “Abstract Syntax Tree” represented as an ast object. By passing this code object into the exec() or eval() functions, you can run it dynamically in your Python code. This way, you can programmatically create source code and execute it at runtime. To use the function, pass the string code to be executed, the filename, and the execution mode. For example compile('print("hi")', '<string>', 'exec') creates a code object consisting of one line print("hi").

# 1. Read code from file
f = open('filename.py', 'r')
code = f.read()
f.close()

# 2. Compile code string
code_obj = compile(code, 'filename.py', 'exec')

# 3. Run the code object (ast)
exec(code_obj)

abs()

Python’s built-in abs(x) function returns the absolute value of the argument x that can be an integer, float, or object implementing the __abs__() function. For a complex number, the function returns its magnitude. The absolute value of any numerical input argument -x or +x is the corresponding positive value +x.

# POSITIVE INTEGER
x = 42
print(abs(x))


# NEGATIVE INTEGER
x = -42
print(abs(x))


# POSITIVE FLOAT
x = 42.42
print(abs(x))


# NEGATIVE FLOAT
x = -42.42
print(abs(x))

divmod()

Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b). The first tuple value is the result of the integer division a//b. The second tuple is the result of the remainder, also called modulo operation a % b. In case of float inputs, divmod() still returns the division without remainder by rounding down to the next round number.

# divmod() with integers
>>> divmod(10, 2)
(5, 0)
>>> divmod(10, 3)
(3, 1)
>>> divmod(10, 4)
(2, 2)
>>> divmod(10, 5)
(2, 0)
>>> divmod(10, 10)
(1, 0)

round()

Python’s built-in round() function takes two input arguments: a number and an optional precision in decimal digits. It rounds the number to the given precision and returns the result. The return value has the same type as the input number—or integer if the precision argument is omitted. Per default, the precision is set to 0 digits, so round(3.14) results in 3.

>>> round(3.14)
3
>>> round(3.14, ndigits=1)
3.1
>>> round(3.13, ndigits=-1)
0.0
>>> round(4458.1242, ndigits=-1)
4460.0
>>> round(3.14159, ndigits=3)
3.142

hash()

Python’s built-in hash(object) function takes one object as an argument and returns its hash value. As the hash value is calculated based on the object’s data, two different but equal objects must have the same hash value. It doesn’t follow, though, that two objects with the same hash value are equal—they can have the same hash value and still be different.

>>> hash(42)
42
>>> hash('42')
-7286207279771019371

callable()

Python’s built-in callable(object) returns True if you could call the object argument like a function with the trailing parentheses in object(). You can make any object callable by implementing the instance’s __call__() method. For example, callable(callable) returns True because callable is a function object. But callable(3) returns False because an integer is not a function you can call.

>>> callable(callable)
True
>>> callable(3)
False

iter()

Python’s built-in iter() function returns an iterator for the given object. For example, iter([1, 2, 3]) creates an iterator for the list [1, 2, 3]. You can then iterate over all elements in the iterator, one element at a time, in a for or while loop such as: for x in iter([1, 2, 3]).

customers = ['Alice', 'Bob', 'Carl', 'Dave', 'Elena', 'Frank']
iterator = iter(customers)

print(next(iterator))
print(next(iterator))

for x in iterator:
    print(x)

''' OUT:
Alice
Bob
Carl
Dave
Elena
Frank
'''

Every Python master understands the basics very well. Python built-in functions are the very foundation your whole coding career stands on. For a full course on all 64 Python built-in functions, check out the Finxter Computer Science Academy:

next()

The next(iterator) function is one of Python’s built-in functions—so, you can use it without importing any library. It returns the next value from the iterator you pass as a required first argument. An optional second argument default returns the passed default value in case the iterator doesn’t provide a next value.

users = ['Alice', 'Bob', 'Carl', 'David']

# convert the list to an iterator
users_iterator = iter(users)

x = next(users_iterator)
print(x)
# Output: 'Alice'

x = next(users_iterator)
print(x)
# Output: 'Bob'

x = next(users_iterator)
print(x)
# Output: 'Carl'

x = next(users_iterator)
print(x)
# Output: 'David'

list()

The Python range() function creates an iterable of subsequent integers within a given range of values. You can pass either only a stop argument in which case the range object will include all integers from 0 to stop (excluded). Or you can pass start, stop, and step arguments in which case the range object will go from start to step using the given step size. For example, range(3) results in 0, 1, 2 and range(2, 7, 2) results in 2, 4, 6.

>>> x = [1, 2, 3]
>>> y = list(x)
>>> x is y
False
>>> x == y
True

range()

The Python range() function creates an iterable of subsequent integers within a given range of values. You can pass either only a stop argument in which case the range object will include all integers from 0 to stop (excluded). Or you can pass start, stop, and step arguments in which case the range object will go from start to step using the given step size. For example, range(3) results in 0, 1, 2 and range(2, 7, 2) results in 2, 4, 6.

>>> range(10)
range(0, 10)
>>> print(range(10))
range(0, 10)
>>> print(*range(10))
0 1 2 3 4 5 6 7 8 9
>>> range(1, 10, 3)
range(1, 10, 3)
>>> print(*range(1, 10, 3))
1 4 7

len()

Python’s built-in function len() returns the length of the given string, array, list, tuple, dictionary, or any other iterable. The type of the return value is an integer that represents the number of elements in this iterable.

>>> friends = ['Alice', 'Bob', 'Carl', 'Ann']
>>> len(friends)
4
>>> friends.extend([1, 2, 3])
>>> len(friends)
7
>>> len('hello world')
11
>>> len('hi')
2
>>> len((1, 2, 3))
3
>>> len({42, 21})
2
>>> age = {'Alice': 18, 'Bob': 21}
>>> len(age)
2
>>> age['Carl'] = 33
>>> len(age)
3

max()

The max() function returns the maximum of the provided arguments. You can pass either an arbitrary number of values, comma-separated, or an iterable as arguments. An optional key function argument allows you to customize the calculation of the maximum by explicitly defining the weight of each value in the iterable that is used as a basis of comparison.

>>> max(1, 2, 3)
3
>>> max(1, 2, 3, key = lambda x: -x)
1

min()

The min() function returns the minimum of the provided arguments. As arguments, you can either pass a number of comma-separated values, or a single iterable. An optional key function argument allows you to customize the calculation of the minimum by explicitly defining the weight of each value in the iterable that is used as a basis of comparison.

>>> min(1, 2, 3)
1
>>> min(1, 2, 3, key = lambda x: -x)
3

Every Python master understands the basics very well. Python built-in functions are the very foundation your whole coding career stands on. For a full course on all 64 Python built-in functions, check out the Finxter Computer Science Academy:

sum()

To help you accomplish this task in a concise, readable, and efficient way, Python’s creators have added the built-in sum() function. It sums over all elements in a Python list—or any other iterable for that matter.

lst = [1, 2, 3, 4, 5, 6]

print(sum(lst))
# 21

print(sum(lst, 10))
# 31

slice()

Python’s built-in slice() function returns a new slice object you can use to slice over sequences such as lists, strings, or tuples.

>>> lst =list(range(20))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> s = slice(10)
>>> lst[s]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst =list(range(20))
>>> s = slice(2, 10, 2)
>>> lst[s]
[2, 4, 6, 8]

enumerate()

Python’s built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters. Formally, it takes an iterable as an input argument and returns an iterable of tuples (i, x)—one per iterable element x. The first integer tuple value is the counter of the element x in the iterable, starting to count from 0. The second tuple value is a reference to the element x itself. For example, enumerate(['a', 'b', 'c']) returns an iterable (0, 'a'), (1, 'b'), (2, 'c'). You can modify the default start index of the counter by setting the optional second integer argument enumerate(iterable, start).

fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits):
    print(counter, value)

# OUTPUT:
# 0 apple
# 1 banana
# 2 cherry

reversed()

Python’s built-in reversed(sequence) function returns a reverse iterator over the values of the given sequence such as a list, a tuple, or a string.

>>> list(reversed([1, 2, 3]))
[3, 2, 1]
>>> tuple(reversed([1, 2, 3]))
(3, 2, 1)

Every Python master understands the basics very well. Python built-in functions are the very foundation your whole coding career stands on. For a full course on all 64 Python built-in functions, check out the Finxter Computer Science Academy:

sorted()

The sorted() function takes a specified iterable input and returns a sorted list

>>> x = [4, 1, 2]
>>> sorted(x)
[1, 2, 4]

filter()

Python’s built-in filter() function is used to filter out elements that pass a filtering condition. It takes two arguments: function and iterable. The function assigns a Boolean value to each element in the iterable to check whether the element will pass the filter or not. It returns an iterator with the elements that pass the filtering condition.

lst = [8, 2, 6, 4, 3, 1]

# Filter all elements <8
small = filter(lambda x: x<8, lst)
print(list(small))


# Filter all even elements
even = filter(lambda x: x%2==0, lst)
print(list(even))

# Filter all odd elements
odd = filter(lambda x: x%2, lst)
print(list(odd))

map()

>>> m = map(lambda x: 42, [1, 2, 3])
>>> type(m)
<class 'map'>

any()

The zip() function takes an arbitrary number of iterables and aggregates them to a single iterable, a zip object. It combines the i-th values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

# Boolean list with False value
print(any([True, False, True, True]))
# True


# Boolean list without False value
print(any([True, True]))
# True


# Integer list with 0 value
print(any([1, 2, -1, 0]))
# True


# Integer list without 0 value
print(any([1, 2, -1]))
# True


# Nested list with empty inner list
print(any([[], [1, 2, 3]]))
# True


# Nested list with two empty inner lists
print(any([[], []]))
# False


# Empty List
print(any([]))
# False

all()

The zip() function takes an arbitrary number of iterables and aggregates them to a single iterable, a zip object. It combines the i-th values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

# Boolean list with False value
print(all([True, False, True, True]))
# False


# Boolean list without False value
print(all([True, True]))
# True


# Integer list with 0 value
print(all([1, 2, -1, 0]))
# False


# Integer list without 0 value
print(all([1, 2, -1]))
# True


# List of Lists with empty inner list
print(all([[], [1, 2, 3]]))
# False


# List of Lists without empty inner list
print(all([[1, 2, 3], [4, 5]]))
# True


# Empty List
print(all([]))
# True

zip()

The zip() function takes an arbitrary number of iterables and aggregates them to a single iterable, a zip object. It combines the i-th values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

lst_1 = [1, 2, 3]
lst_2 = [4, 5, 6]

# Zip two lists together
zipped = list(zip(lst_1, lst_2))
print(zipped)
# [(1, 4), (2, 5), (3, 6)]


# Unzip to lists again
lst_1_new, lst_2_new = zip(*zipped)
print(list(lst_1_new))
print(list(lst_2_new))

Every Python master understands the basics very well. Python built-in functions are the very foundation your whole coding career stands on. For a full course on all 64 Python built-in functions, check out the Finxter Computer Science Academy:

The post Python’s Top 29 Built-In Functions with Examples first appeared on Finxter.

Python

via Finxter https://ift.tt/2HRc2LV

March 15, 2021 at 06:11AM