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))
<strong>Output: </strong>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))

<strong>Output:</strong> 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(" ")
print(words)
<strong>Output:</strong> ['column1', 'column2', 'column3']

Related: How to Split a String in Python

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)

<strong>Output:</strong>
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)
<strong>Output:</strong>
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)
print(d)
<strong>Output:</strong> 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)

<strong>Output:</strong>
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"}
print(max(b.values()))
<strong>Output:</strong> 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]
print(max(a))
<strong>Output:</strong> 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]
print(min(a))
print(min(b.values()))

<strong>Output:</strong>
1
apple

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]

<strong># Declare a separate function to handle the addition:</strong>
def add(a, b):
return a+b

<strong># Pass the function and the two lists into the built-in map() function:</strong>
a = sum(map(add, b, a))
print(a)
<strong>Output:</strong> 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
self.name = name

a = ty(5*8, "Idowu")

b = getattr(a, 'name')
print(b)

<strong>Output:</strong>Idowu

Related:Instance vs. Static vs. Class Methods in Python: The Important Differences

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.

Related:How to Append a List in Python

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
appendedlist.append(a)
print(appendedlist)

<strong>Output:</strong>[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:
b.append(i)
print(b)

<strong>Output:</strong> [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)

print(b[sliceportion])
print(st[sliceportion])
<strong>Output:</strong>
[1, 3, 4, 6]
Pyth

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

        print(b[0:4])
print(st[0:4])

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)
print(a)

<strong>Output:</strong>
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")
print(st)
<strong>Output:</strong> 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)
print(pos)
<strong>Output:</strong> 5

16. upper()

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

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

<strong>Output:</strong> PYTHON TUTORIAL

17. lower()

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

        y = "PYTHON TUTORIAL"
y = y.lower()
print(y)

<strong>Output:</strong> 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)

<strong>Output:</strong>
[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)
print(a)

<strong>Output:</strong> 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("_", " ")
print(i)
<strong>Output:</strong>
Cart name
First name
Last name

Keep Learning to Build on Python’s Power

As a compiled, higher-level programming language, with vast community support, Python keeps receiving many additional functions, methods, and modules. And while we've covered a majority of the popular ones here, studying features such as regular expressions, and looking deeper into how they work in practice, will help you keep up with the pace of Python's evolution.