Start Using These Python Functions Now
5 Python functions every programmer must know
Many beginners often find coding in Python to be complicated and time-consuming, when in reality, the language has an extremely simplified syntax compared to other programming languages. These beginners do not realize that the long segments of their code they wasted significant time on writing are usually replaceable with one-liners that perform faster and better. Even experienced and intermediate programmers miss out on many of Python’s built-in functions, costing them time and effort. To be successful in programming, an arsenal consisting of several of these functions is a necessity. Thus, here are 5 such functions every programmer should be using in their programs.
1. The eval() function
The eval() function is extremely useful due to its capability to evaluate any specified mathematical expression. This function can take in three parameters:
- The mathematical expression to be evaluated, in the form of a string.
- An optional parameter that takes in a dictionary that references global variables to
eval(). For example, by referencing the character “x” to a global variable named “number”, you will be able to use “x” as a representation of the value assigned to “number” in the first parameter (the expression). - An optional parameter that takes in a dictionary that allows the direct assignment to variables specified in the expression. For instance, if a variable “x” is used in the expression, you can reference “x” to a numerical value in a dictionary. In contrast to the second parameter which links to global variables outside of the function, this parameter is used to create new local variables inside the function.
The eval() function can solve mathematical expressions of any length in your code without using numerous if statements to check for varying operations in a complicated and time-consuming process.
Example:
# outputting the evaluation of the expression 1+3*5
print(eval('1+3*5'))
# Output: 16# add the value of the global variable "number" to the expression in # the form of x (the second parameter)
number = 1
print(eval('1+3*5+x', {'x': number}))
# Output: 17# creating a local variable named "x" and assigning it to 10
print(eval('1+3*5+x', {}, {'x': 10}))
# Output: 262. The join() function
The join() function returns a string created from joining the string elements of a given sequence. This function takes in one parameter only:
- The iterable specifying the strings to be joined by the function. All values of this iterable must be strings.
However, a separator must be specified which will be used to connect the values in the specified iterable. This string will go before the function and be connected to it through a dot. Here is the full syntax:
separator.join(iterable)
This function serves as an alternative to the traditional method of joining strings, which employs the use of loops and an accumulator (adding strings together concatenates/joins them). join()is also faster performance-wise.
Example:
sequence = ['Ta', 'n', 'dr', 'ew']# joining a sequence without connecting them with any character
# using an empty string to connect the sequence
separator = ''# output the joined string
print(separator.join(sequence))
# Output: Tandrew3. The sum() function
As its name suggests, the sum() function returns the sum of the values in an iterable (list, tuple, etc). This function takes in two parameters:
- The iterable containing the sequence the function will find the sum of.
- An optional parameter, an extra value added to the final sum/return value.
The sum() function is an excellent alternative to the traditional method of finding the sum of the values of an iterable, which involves using a loop in unison with an accumulator (a variable responsible for accumulating the values in a sequence).
Example:
sequence = [1, 2, 3]# output sum of sequence
print(sum(sequence))
# Output: 6# output sum of sequence added to 10
print(sum(sequence, 10))
# Output: 164. The sorted() function
The sorted() function returns a sorted version of the specified iterable. This function can take in 3 parameters:
- The iterable that the function will be responsible for sorting.
- An optional parameter is a “key” function that allows the user to modify the sorting process with the function's return value. For instance, if the user wants to sort a 2-dimensional list (list of lists) by the lengths of each list, they would specify the
len()function. This function would be applied to every list inside the 2-dimensional list to acquire their lengths, and the program would sort these lists by comparing their lengths instead. - “Reverse”, an optional parameter that takes in a boolean. This parameter determines if the specified iterable would be sorted in an ascending or descending order. False, the default argument, results in sorting in ascending order. True will result in descending order.
sorted() utilizes Tim Sort, one of the fastest sorting algorithms. This makes it a suitable alternative to most sorting algorithms, on top of being customizable and easy to implement in your code.
Example:
sequence = [3, 5, 4, 2, 1]
sequence2 = [[1, 2], [3, 2, 4], [1], [1, 1, 2, 3]]# output sorted sequence
print(sorted(sequence))
# Output: [1, 2, 3, 4, 5]# output sequence2 sorted by the lengths of its lists
print(sorted(sequence2, key=len))
# Output: [[1], [1, 2], [3, 2, 4], [1, 1, 2, 3]]# output sequence sorted in descending/reversed order
print(sorted(sequence, reverse=True))
# Output: [5, 4, 3, 2, 1]5. The map() function
The map() function allows the application of a function to every element of an iterable. This function takes in two parameters:
- A function that will be executed by passing the values obtained from the iterable into its parameters. The contents of the function are essentially identical to the code you would write under your standard for loop, which will process each data value in the referenced iterable.
- The iterable that the map function will be looping through.
The map() function is a great substitute for loops, being substantially faster and shorter.
Example:
sequence = [[4, 2], [3, 2, 4], [1], [1, 4, 2, 3]]# sort the lists within the sequence in ascending order
# map returns a map object and needs to be casted into a list
print(list(map(sorted, sequence)))
# Output: [[2, 4], [2, 3, 4], [1], [1, 2, 3, 4]]For more tips and tricks involving the map() function, visit this article:
Conclusion
Python’s extensive library is a powerful tool that many programmers fail to fully exploit. Excessive blocks of code can often be substituted by one-liners, or modified to be shorter and more efficient. Applying the knowledge of built-in functions is necessary for efficient coding and is often what separates a proficient programmer from beginners and amateurs. Doing so will not only refine your code but also fundamentally impact your programming abilities.
Thank you for reading. Follow and subscribe to Shu Hasegawa to get notified of new content that can help you get started on your programming career.
