Python - Interview Questions basics.
Interview Questions.
- List is mutable. Tuple is immutable.
- List consume more memory and slow. Tuple consume less memory and fast.
- When you are returning something from the function the returned value is tuple.
Difference between map, filter and reduce with example?
Map - The map() function is a higher-order function. As previously stated, this function accepts another function and a sequence of ‘iterables’ as parameters and provides output after applying the function to each iterable in the sequence. It has the following syntax:
SYNTAX: map(function, iterables)
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Firstly, map will compute it will return output as a square of each elements inside a list i.e., [1, 4, 9, 16, 25, 36] now filter will only take those element from which the function will be true. As the function is saying take only those element which is greater than 10. So the final result will be [16, 25, 36].
Filter - The filter() function is used to generate an output list of values that return true when the function is called. It has the following syntax:
SYNTAX: filter (function, iterables)
Firstly, the filter function will take only those element which will be greater than the 2. from the given list only [3, 4, 5, 6] is greater than 2. Now, will apply map function on these new elements as the map function is saying take square the given element. hence, output will be [9, 16, 25, 36]Reduce - The reduce() function applies a provided function to ‘iterables’ and returns a single value, as the name implies.
SYNTAX: filter (function, iterables)
The function tools module must be used to import this function.
from functools import reduce.
To use reduce we have to first import it. As what I did in second line.
Creating a list of integers. in third line.
Firstly, map will give it's output as we are squaring the elements so the output will be [1, 4, 9, 16, 25, 36]. After that we are filtering out, so updated output will be [16, 25, 36]. Now we know that reduce will give a single output. As lambda function of reduce is doing the addition, like firstly adding 16 + 25 = 41, now adding 41 + 36 = 77. Hence, our final output is 77.
Local and Global Variables in python ?
Global Variables - Are those which are not defined inside any function.
Local Variables - Are those which are defined inside a function.
Example:
def f():
# local variable
s = "I love Coding"
print("Inside Function:", s)
# Driver code
f()
print(s) # Name error name s is not defined.
.png)
.png)
.png)
Comments
Post a Comment