Useful methods

sum()


# A sum of a list's elements (also works with tuples, etc.)
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(sum(x))
                                    

sorted() and sort()

These two methods sort a collection (if it contains letters, alphabetically). They differ in that sort() modifies the original list in place and returns None, while sorted() returns a new sorted list and leaves the original iterable unchanged. While sort() works only for lists, sorted() can also be used for other iterables (tuples, strings, etc.)


x = ["b", "d", "a", "c"]
print(sorted(x))

y = ["b", "d", "a", "c"]
y.sort()
print(y)  
                                    

Both methods accept keyword arguments, such as key and reverse = True, to customize the sorting behavior.

round()


# Rounding a number to the nearest integer
x = 5.4
print(round(x))
                                    

id()


# Checking the object's ID in memory (its memory address)
x = 5
print(id(x))
                                    

abs()


# An absolute value of a number
x = abs(-5)
print(x)
                                    

eval()

The eval() function takes a string with a mathematical expression or Python code and calculates/runs it. Its version from the ast module, literal_eval(), takes a string with a literal (a list, a dict, etc.) and turns it into a data structure we can operate on. It is safer to use for this purpose because it prevents executing other code.


expression = "3 * (4 + 5)"
result = eval(expression)
print(result)
                                    

def func1():
    print("func1 call")

def func2():
    print("func2 call")

functions = ["func1", "func2"]
for x in functions:
    eval(x)() # calling the functions from the list
                                    

import ast
literal_list = "[1, 2, 3, 4, 5]"
literal_dict = "{'a': 1, 'b': 2}"
result_list = ast.literal_eval(literal_list)
result_dict = ast.literal_eval(literal_dict)
print(result_list)
print(result_dict)
                                    

compile() and exec()

The compile() function takes a string with Python code, converts it to "code," and exec() executes it.


code = """
for i in range(5):
    print(i)
"""
compiled_code = compile(code, "<string>", "exec")
exec(compiled_code)
                                    

callable()


# Checking whether an object can be called
def func():
    pass
x = 5
print(callable(func))
print(callable(x))