You Should Know These 20 Python Functions

You Should Know These 20 Python Functions

python range, python random, python join, python max, python abs, python getattr, getattr


Writing less code is a fantastic technique to create programmes that are more legible and functional. You shouldn't waste time replicating Python functions or methods that already exist. If you're unfamiliar with Python's built-in tools, you might wind up doing this. Here's a collection of useful built-in Python functions and techniques for shortening and improving your code.


1. reduce()

reduce() delivers a single value after iterating over each item in a list or any other iterable data type in Python.“It's one of the built-in functools class of Python's methods.”

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

The reduce() function can also be used to format a list of strings:


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


2. split()

The split() function divides a text into segments based on a list of criteria. It can be used to split a web form's string value. You may also use it to count how many words are in a piece of text.

The following code separates a list wherever a space exists:


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

Also Read:  Packing and Unpacking Arguments in Python

3. enumerate()

The enumerate() function returns an iterable's length and runs through its components at the same time. As a result, while displaying each item in an iterable data type, it also prints the index.

Assume you want a user to be able to see the list of things in your database. You can pass them into a list and use the enumerate() function to return this as a numbered list. Using the enumerate() method, you can accomplish this:


fruits = ["banana", "strawberry", "pineapple"]
for i, j in enumerate(fruits):
print(i, j)
Output: 0 banana 1 strawberry 2 pineapple

Alternatively, you may have squandered time by utilising the following method:


fruits = ["banana", "strawberry", "pineapple"]
for i in range(len(fruits)):
print(i, fruits[i])

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


4. eval()

The eval() function in Python allows you to execute mathematical operations on integers and floats in textual form. A string format for a mathematical calculation is frequently useful.

The following is how it works:

 
g = "(8 * 3)/4"
d = eval(g)
print(d)
Output: 6.0
Also Read: For 2022, the Best Javascript Frameworks

5. round()

The round() function can be used to round the result of a mathematical operation to a given number of significant figures:


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)
Output: The raw average is: 11.333333333333334 The rounded average is: 11.33


6.max()

The function returns the item in an iterable with the highest rank. But be careful not to mix this up with the value that appears the most frequently.

Using the max() method, display the highest ranking value in the dictionary below:


b = {1:"grape", 2:"apple", 3:"applesss", 4:"zebra", 5:"mango"}
print(max(b.values()))
Output: zebra

The above code alphabetizes the elements in the dictionary and prints the last one. To find the largest integer in a list, use the max()function:


a = [1, 65, 7, 9]
print(max(a))
Output: 65


7. min()

The min() function accomplishes the inverse of the max() function:


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()))
Output: 1 apple


8. map()

The map() method, like reduce(), allows you to iterate over each item in an iterable. map(), on the other hand, operates on each item separately rather than producing a single output. Finally, the map() method can be used to perform mathematical operations on two or more lists. It can also be used to manipulate an array of any data type.

Using the map() method, find the cumulative total of two lists containing integers:


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)
Output: 96


9. getattr()

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

Here's an illustration:


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


10. append()

append() is a Python method that you'll use a lot whether you're doing web development or machine learning with Python. It operates by inserting new data into a list without erasing the existing data.

Each item in a range of integers is multiplied by three and written into an existing list in the example below:


nums = [1, 2, 3]
appendedlist = [2, 4]
for i in nums:
a = i*3
appendedlist.append(a)
print(appendedlist)
Output: [2, 4, 3, 6, 9]


11. range()

You may already be familiar with Python's range() function. It's useful if you want to generate a list of integers spanning between two values without having to write them out manually.

Let's use this function to make a list of odd numbers between one and five:


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


12. slice()

Despite the fact that the slice() function and the standard slice technique produce equivalent results, utilizing slice() in your code can improve readability.

The slice method can be used to slice any changeable iterable:


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

When you use the classic way below, the above code produces a similar result:


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


13. format

The format() method allows you to alter the output of a string. The following is 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)
Output: 10 is the multiple of 5 and 2, but 14 is for 7 and 2


14. strip

The strip() function in Python removes leading characters from a string. If the initial character in the string matches any of the specified characters, it is repeatedly removed from the string.

Strip removes all beginning whitespace characters from the string if you don't provide a character.

The following code removes the letter P from the string, as well as the space before it:

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


15. abs

Are you looking for a way to cancel away unfavorable mathematical results? Then give the abs() function a shot. It can be useful in tasks such as computational programming or data science.

See how it works in the example below:


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


16. upper

The upper() method turns string characters to uppercase equivalents, as the name implies:


y = "Python tutorial"
y = y.upper()
print(y)
Output: PYTHON TUTORIAL


17. lower

You guessed correctly! lower() in Python is the inverse of upper(). As a result, it lowercases string characters:


y = "PYTHON TUTORIAL"
y = y.lower()
print(y)
Output: python tutorial


18. sorted

The sorted() function creates a list from an iterable and then sorts the items in ascending or descending 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)
Output: [9, 4, 3, 1] [3, 5, 8, 9]


19. Join()

You can use the join() function to join string items in a list.

To use it, you merely need to specify a delimiter and a target list:


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


20. replace()

The replace() function in Python allows you to swap out characters in a string. It comes in helpful a lot in data science, especially when cleaning up data.

The replace() function takes two arguments: the replaced character and the replacement character.

The following is how it works:


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


Continue to learn more about Python's capabilities.

Python, as a compiled, higher-level programming language with a large community, continues to gain new functions, methods, and modules. While we've covered the majority of the most common ones here, understanding features like regular expressions and learning more about how they function in reality can help you keep up with Python's progress.


Also Read: 

Post a Comment

0 Comments