Press "Enter" to skip to content

20 Python Functions You Should Know

Writing less code is a great way of crafting more readable, functional programs. You shouldn’t waste valuable time recreating Python functions or methods that are readily available. You might end up doing this if you’re not familiar with Python’s built-in tools, though.

Here’s a list of valuable built-in Python functions and methods that shorten your code and improve its efficiency.

1. reduce()

Python’s reduce() function iterates over each item in a list, or any other iterable data type, and returns a single value. It’s one of the methods of the built-in functools class of Python.

Here’s an example of how to use reduce:

from functools import reduce
def add_num(a, b):
return a+b
a = [1, 2, 3, 10]
print(reduce(add_num, a))
Output: 16

You can also format a list of strings using the reduce() function:

from functools import reduce
def add_str(a,b):
return a+' '+b
a = ['MUO', 'is', 'a', 'media', 'website']
print(reduce(add_str, a))
Output: MUO is a media website

2. split()

The split() function breaks a string based on set criteria. You can use it to split a string value from a web form. Or you can even use it to count the number of words in a piece of text.

The example code below splits a list wherever there’s a space:

words = "column1 column2 column3"
words = words.split(" ")
Output: ['column1', 'column2', 'column3']

3. enumerate()

The enumerate() function returns the length of an iterable and loops through its items simultaneously. Thus, while printing each item in an iterable data type, it simultaneously outputs its index.

Assume that you want a user to see the list of items available in your database. You can pass them into a list and use the enumerate() function to return this as a numbered list.

Here’s how you can achieve this using the enumerate() method:

fruits = ["grape", "apple", "mango"]
for i, j in enumerate(fruits):
print(i, j)
0 grape
1 apple
2 mango

Whereas, you might’ve wasted valuable time using the following method to achieve this:

fruits = ["grape", "apple", "mango"]
for i in range(len(fruits)):
print(i, fruits[i])

In addition to being faster, enumerating the list lets you customize how your numbered items come through.

In essence, you can decide to start numbering from one instead of zero, by including a start parameter:

for i, j in enumerate(fruits, start=1):
print(i, j)
1 grape
2 apple
3 mango

4. eval()

Python’s eval() function lets you perform mathematical operations on integers or floats, even in their string forms. It’s often helpful if a mathematical calculation is in a string format.

Here’s how it works:

g = "(4 * 5)/4"
d = eval(g)
Output: 5.0

5. round()

You can round up the result of a mathematical operation to a specific number of significant figures using round():

raw_average = (4+5+7/3)
rounded_average=round(raw_average, 2)
print("The raw average is:", raw_average)
print("The rounded average is:", rounded_average)
The raw average is: 11.333333333333334
The rounded average is: 11.33

6. max()

The max() function returns the highest ranked item in an iterable. Be careful not to confuse this with the most frequently occurring value, though.

Let’s print the highest ranked value in the dictionary below using the max() function:

b = {1:"grape", 2:"apple", 3:"applesss", 4:"zebra", 5:"mango"}
Output: zebra

The code above ranks the items in the dictionary alphabetically and prints the last one.

Now use the max() function to see the largest integer in a list:

a = [1, 65, 7, 9]
Output: 65

7. min()

The min() function does the opposite of what max() does:

fruits = ["grape", "apple", "applesss", "zebra", "mango"]
b = {1:"grape", 2:"apple", 3:"applesss", 4:"zebra", 5:"mango"}
a = [1, 65, 7, 9]

8. map()

Like reduce(), the map() function lets you iterate over each item in an iterable. However, instead of producing a single result, map() operates on each item independently.

Ultimately, you can perform mathematical operations on two or more lists using the map() function. You can even use it to manipulate an array containing any data type.

Here’s how to find the combined sum of two lists containing integers using the map() function:

b = [1, 3, 4, 6]
a = [1, 65, 7, 9]
# Declare a separate function to handle the addition:
def add(a, b):
return a+b
# Pass the function and the two lists into the built-in map() function:
a = sum(map(add, b, a))
Output: 96

9. getattr()

Python’s getattr() returns the attribute of an object. It accepts two parameters: the class and the target attribute name.

Here’s an example:

class ty:
def __init__(self, number, name):
self.number = number = name
a = ty(5*8, "Idowu")
b = getattr(a, 'name')

10. append()

Whether you’re delving into web development or machine learning with Python, append() is another Python method you’ll often need. It works by writing new data into a list without overwriting its original content.

The example below multiplies each item in a range of integers by three and writes them into an existing list:

nums = [1, 2, 3]
appendedlist = [2, 4]
for i in nums:
a = i*3
Output:[2, 4, 3, 6, 9]

11. range()

You might already be familiar with range() in Python. It’s handy if you want to create a list of integers ranging between specific numbers without explicitly writing them out.

Let’s create a list of the odd numbers between one and five using this function:

a = range(1, 6)
b = []
for i in a:
if i%2!=0:
Output: [1, 3, 5]

12. slice()

Although the slice() function and the traditional slice method give similar outputs, using slice() in your code can make it more readable.

You can slice any mutable iterable using the slice method:

b = [1, 3, 4, 6, 7, 10]
st = "Python tutorial"
sliceportion = slice(0, 4)
[1, 3, 4, 6]

The above code gives a similar output when you use the traditional method below:


13. format()

The format() method lets you manipulate your string output. Here’s how it works:

multiple = 5*2
multiple2 = 7*2
a = "{} is the multiple of 5 and 2, but {} is for 7 and 2"
a = a.format(multiple, multiple2)
10 is the multiple of 5 and 2, but 14 is for 7 and 2

14. strip()

Python’s strip() removes leading characters from a string. It repeatedly removes the first character from the string, if it matches any of the supplied characters.

If you don’t specify a character, strip removes all leading whitespace characters from the string.

The example code below removes the letter P and the space before it from the string:

st = " Python tutorial"
st = st.strip(" P")
Output: ython tutorial

You can replace (” P”) with (“P”) to see what happens.

15. abs()

Do you want to neutralize negative mathematical outputs? Then try out the abs() function. It can come in handy in computational programming or data science operations.

See the example below for how it works:

neg = 4 - 9
pos = abs(neg)
Output: 5

16. upper()

As the name implies, the upper() method converts string characters into their uppercase equivalent:

y = "Python tutorial"
y = y.upper()

17. lower()

You guessed right! Python’s lower() is the opposite of upper(). So it converts string characters to lowercases:

y = y.lower()
Output: python tutorial

18. sorted()

The sorted() function works by making a list from an iterable and then arranging its values in descending or ascending order:

f = {1, 4, 9, 3} # Try it on a set
sort = {"G":8, "A":5, "B":9, "F":3} # Try it on a dictionary
print(sorted(f, reverse=True)) # Descending
print(sorted(sort.values())) # Ascending (default)
[9, 4, 3, 1]
[3, 5, 8, 9]

19. join()

The join() function lets you merge string items in a list.

You only need to specify a delimiter and the target list to use it:

a = ["Python", "tutorial", "on", "MUO"]
a = " ".join(a)
Output: Python tutorial on MUO

20. replace()

Python’s replace() method lets you replace some parts of a string with another character. It’s often handy in data science, especially during data cleaning.

The replace() method accepts two parameters: the replaced character and the one you’ll like to replace it with.

Here’s how it works:

columns = ["Cart_name", "First_name", "Last_name"]
for i in columns:
i = i.replace("_", " ")
Cart name
First name
Last name

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *