What is the lambda function in Python?
A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the โlambdaโ keyword instead of the โdefโ keyword, hence the name โlambda functionโ. Lambda functions can have any number of arguments but only one statement.
Example:
A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the โlambdaโ keyword instead of the โdefโ keyword, hence the name โlambda functionโ. Lambda functions can have any number of arguments but only one statement.
Example:
l = lambda x,y : x*y
print(a(5, 6))
Output:30๐19โค2
Here's a list of 20 valuable built-in Python functions and methods that shorten your code and improve its efficiency.
โค10๐1
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:
You can also format a list of strings using the reduce() function:
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 reduceOutput: 16
def add_num(a, b):
return a+b
a = [1, 2, 3, 10]
print(reduce(add_num, a))
You can also format a list of strings using the reduce() function:
from functools import reduceOutput: MUO is a media website
def add_str(a,b):
return a+' '+b
a = ['MUO', 'is', 'a', 'media', 'website']
print(reduce(add_str, a))
โค6๐2
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:
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"Output: ['column1', 'column2', 'column3']
words = words.split(" ")
print(words)
๐2
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:
0 grape
1 apple
2 mango
Whereas, you might've wasted valuable time using the following method to achieve this:
In essence, you can decide to start numbering from one instead of zero, by including a start parameter:
1 grape
2 apple
3 mango
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"]Output:
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"]In addition to being faster, enumerating the list lets you customize how your numbered items come through.
for i in range(len(fruits)):
print(i, fruits[i])
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):Output:
print(i, j)
1 grape
2 apple
3 mango
๐8
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:
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"Output: 5.0
d = eval(g)
print(d)
๐3
5. round()
You can round up the result of a mathematical operation to a specific number of significant figures using round():
The raw average is: 11.333333333333334
The rounded average is: 11.33
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)Output:
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
๐1
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:
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:
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()))
Output: zebraThe 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
print(max(a))
๐3
7. min()
The min() function does the opposite of what max() does:
1
apple
The min() function does the opposite of what max() does:
fruits = ["grape", "apple", "applesss", "zebra", "mango"]Output:
b = {1:"grape", 2:"apple", 3:"applesss", 4:"zebra", 5:"mango"}
a = [1, 65, 7, 9]
print(min(a))
print(min(b.values()))
1
apple
๐1
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:
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]Output: 96
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)
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:
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:Output:Idowu
def init(self, number, name):
self.number = number
self.name = name
a = ty(5*8, "Idowu")
b = getattr(a, 'name')
print(b)
โค1
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:
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]Output:[2, 4, 3, 6, 9]
appendedlist = [2, 4]
for i in nums:
a = i*3
appendedlist.append(a)
print(appendedlist)
๐2
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:
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)Output: [1, 3, 5]
b = []
for i in a:
if i%2!=0:
b.append(i)
print(b)
๐ฅ6๐1
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:
[1, 3, 4, 6]
Pyth
The above code gives a similar output when you use the traditional method below:
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]Output:
st = "Python tutorial"
sliceportion = slice(0, 4)
print(b[sliceportion])
print(st[sliceportion])
[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])
๐ฅ4๐2
13. format()
The format() method lets you manipulate your string output. Here's how it works:
10 is the multiple of 5 and 2, but 14 is for 7 and 2
The format() method lets you manipulate your string output. Here's how it works:
multiple = 5*2Output:
multiple2 = 7*2
a = "{} is the multiple of 5 and 2, but {} is for 7 and 2"
a = a.format(multiple, multiple2)
print(a)
10 is the multiple of 5 and 2, but 14 is for 7 and 2
๐ฅ5
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:
You can replace (" P") with ("P") to see what happens.
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"Output: ython tutorial
st = st.strip(" P")
print(st)
You can replace (" P") with ("P") to see what happens.
๐ฅ4๐2
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:
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 - 9Output: 5
pos = abs(neg)
print(pos)
๐ฅ2
16. upper()
As the name implies, the upper() method converts string characters into their uppercase equivalent:
As the name implies, the upper() method converts string characters into their uppercase equivalent:
y = "Python tutorial"Output: PYTHON TUTORIAL
y = y.upper()
print(y)
๐2๐ฅ2
17. lower()
You guessed right! Python's lower() is the opposite of upper(). So it converts string characters to lowercases:
You guessed right! Python's lower() is the opposite of upper(). So it converts string characters to lowercases:
y = "PYTHON TUTORIAL"Output: python tutorial
y = y.lower()
print(y)
๐2๐ฅ2
18. sorted()
The sorted() function works by making a list from an iterable and then arranging its values in descending or ascending order:
[9, 4, 3, 1]
[3, 5, 8, 9]
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 setOutput:
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]
๐ฅ2