Table of Contents
Python is one of the most lucrative programming languages. According to research, there were approximately 10 million Python developers in 2020 worldwide and the count is increasing day by day. It provides ease in building a number of applications, web development processes, and a lot more. When it comes to making a program short and clear, we use in-built functions which are a set of statements collectively performing a task. Using in-built functions in a program makes it beneficial in many ways such as:
- Makes it less complex.
- Enhances readability.
- Reduces coding time and debugging time.
- Allows re-usage of code.
Hence, it plays a major role in the development of an application.
Below are a list of valuable built-in Python functions and methods that shorten your code and improve its efficiency.
1. reduce()
Python’s reduce() function repeats over each item in a list, or any other iterable data type, and returns a single value. It is one of the methods of the built-in functools class of Python.
Lets see 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']
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.
Let us suppose 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(fruit+++++++++++++++s):
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 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. You should 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]
# 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))
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
Learn to code from industry experts! Enroll here
10. append()
Whether you are excavating 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
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 helps you to 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()
Using the abs() function, you can neutralize negative mathematical outputs 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()
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()
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.
21. bin()
This function converts an integer to a binary string that has the prefix 0b. Also, the integer passed could be negative or positive. Its time complexity for a number n is O(log(n))
Syntax:
bin(integer)
where the integer is any value passed to receive its binary form.
For Example:
print(bin(8))
Output:
0b1000
22. filter()
This function creates a new iterator from an existing one (such as a list, tuple, or dictionary) that filters elements. It checks whether the given condition is available in the sequence or not and then prints the output. The time complexity of the filter function is O(n).
Syntax:
filter(function, iterable)
where function refers to the function which will be used in a program, iterable refers to the value that will be iterated in the program.
For Example:
c = [‘Ant’,’Lizard’,’Mosquito’,’Snake’]
def vowels(x):
return x[0].lower() in ‘aeiou’
items = filter(vowels, c)
print(list(items))
Output:
['Ant']
Grab the opportunity to learn Python with Entri! Click Here
23. exec()
This function executes the given condition and prints the output in python expression. It executes the program dynamically Python exec() function executes the dynamically created program, which is either a string or a code object. If it is a string, then it is parsed as a Python statement and then executed; else, a syntax error occurs.
Syntax:
exec(object[, globals[, locals]])
where the object can be a string or object code, globals can be a dictionary and the parameter is optional, and locals can be a mapping object and are also optional.
For Example:
exec(print(sum(2,8)))
Output:
10
With these in-built functions, you can make complex applications very easy. Use it whenever you’re working on any Python application to be handy.
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.