Comprehensions
This means to a concise way to create collections like Lists, Dictionaries, or Sets using a single line of code. Following example will explain what it is practically.
Following code captures the Gig interfaces in the traditional way..
Following code will give the same output and it is more Pythonic..
Single line covers it, there are actually 3 sections, let's break it down.
Note:- If we want to get the output in some modified way, as an example in block letters, we can use int.upper() to replace just int which is the expression.
Following example shows how Comprehension works for a Dictionary which outputs the routers which are up.
Lambda Function
A Lambda function in Python is a small, anonymous function defined using the lambda keyword. It's often used for short, simple operations and also called throw away functions after use.
Following example shows a Lambda function which adds 2 given values in single line of code.
Map Function
The map() function in Python applies a function to every item of an iterable (like a List) and returns a map object (which you can convert to a list, tuple, etc.).
Syntax is like the following..
map(function, iterable)
Filter Function
The filter() function in Python is used to filter elements of an iterable (like a List) based on a function that returns True or False.
filter(function, iterable)
The reduce() function in Python is used to apply a function cumulatively to the items of a sequence, reducing the sequence to a single value.
Syntax is like the following..
Syntax is like the following..
reduce(function, iterable)
What this gives is the multiplication of all the values together. 1x2 = 2 then 2x3 = 6 then 6x4 =24 and finally 24x5 = 120
Note:- reduce should be imported from functools library
Here is another example of reduce() function
No comments:
Post a Comment