Advance Features of Python
Last Updated :
19 Feb, 2020
Python is a high-level, interpreted programming language that has easy syntax. Python codes are compiled line-by-line which makes the debugging of errors much easier and efficient. Python works on almost all types of platforms such as Windows, Mac, Linux, Raspberry Pi, etc. Python supports modules and packages, which encourages program modularity and code reuse. Python can be used to deal with large amounts of data and perform complex mathematical problems and can also be used for the development of applications.
Advance Features of Python
Generators
Generator functions allow us to declare a function that behaves the same as an iterator, i.e. it can be used in place of a for loop. Generators are iterators, but they can only iterate over them once. Generators introduce the yield statement in Python which works a bit like return because it returns a value. A generator will create elements and store them in memory only as it needs them i.e one at a time. That means, if you have to create a large amount of floating-point numbers, you’ll only be storing them in memory one at a time!. This greatly simplifies the code and makes the code more efficient than a simple for loop.
Example 1:-
def my_func():
n = 1
print ( 'First Number' )
yield n
n + = 1
print ( 'Second Number ' )
yield n
n + = 1
print ( 'Last Number ' )
yield n
for number in my_func():
print (number)
|
Output:
First Number
1
Second Number
2
Last Number
3
Example 2:-
def str (my_str):
length = len (my_str)
for i in range ( 0 , length ):
yield my_str[i]
for char in str ( "Shivam And Sachin" ):
print (char, end = "")
|
Output:
Shivam And Sachin
Note: For more information, refer to Generators in Python
Decorator
Decorators are amongst the significant part of Python. They are very helpful to add functionality to a function that is implemented before without making any change to the original function. In Decorators, functions are passed as the argument into another function and then called inside the wrapper function. They allow us to wrap another function in order to extend the functionality of a wrapped function, without permanently modifying it. Decorators are usually called before the definition of a function you want to decorate. A decorator is very efficient when you want to give an updated code to existing code.
Example 1:-
def decorator(a_func):
def wrapper():
print ( "Before executing function requiring decoration." )
a_func()
print ( "After executing requiring decoration." )
return wrapper
def function():
print ( "Function requiring decoration." )
function()
function = decorator(function)
function()
|
Output:
Function requiring decoration.
Before executing function requiring decoration.
Function requiring decoration.
After executing requiring decoration.
Example 2:-
def flowerDecorator(func):
def newFlowerPot(n):
print ( "We are decorating the flower vase." )
print ( "You wanted to keep % d flowers in the vase." % n)
func(n)
print ( "Our decoration is done." )
return newFlowerPot
def flowerPot(n):
print ( "We have a flower vase." )
flowerPot = flowerDecorator(flowerPot)
flowerPot( 5 )
|
Output:
We are decorating the flower vase.
You wanted to keep 5 flowers in the vase.
We have a flower vase.
Our decoration is done.
Note: For more information, refer to Decorators in Python
Lambda Functions
Lambda function is a small anonymous function. These types of function can take any number of arguments but can have only one expression. Normal functions are defined using the def
keyword whereas anonymous functions are defined using the keyword “lambda
“. Lambda functions do not require the return statement, they always return the value obtained by evaluating the lambda expression.
Example:- Code for multiplying 3 numbers.
x = lambda a, b, c : a * b * c
print (x( 5 , 4 , 3 ))
|
Output:
60
Example:- Code for adding 3 numbers.
x = lambda a, b, c : a + b + c
print (x( 12 , 40 , 8 ))
|
Output:
60
Note: For more information, refer to Python lambda
Map
Map()
is an inbuilt Python function used to apply a function to a sequence of elements such as a list or a dictionary and returns a list of the results. Python map object is an iterator, so we can iterate over its elements. We can also convert map objects to sequence objects such as list, tuple, etc. It’s an easy and efficient way to perform operations such as mapping two lists or sequencing elements of a list or dictionary.
Example:- Code to convert string to its length.
def func(n):
return len (n)
a = ( 'Singla' , 'Shivam' , 'Sachin' )
x = map (func, a)
print (a)
print ( list (x))
|
Output:
('Singla', 'Shivam', 'Sachin')
[6, 6, 6]
Example:- Code to map number to its cube.
numbers = ( 1 , 2 , 3 , 4 )
res = map ( lambda x: x * x * x, numbers)
numbersCube = list (res)
print (numbersCube)
|
Output:
[1, 8, 27, 64]
Note: For more information, refer to Python map() function
Filter
Filter()
is an inbuilt function that is quite similar to the Map function as it applies a function to a sequence (tuple, dictionary, list). The key difference is that filter() function takes a function and a sequence as arguments and returns an iterable, only yielding the items in sequence for which function returns True and all the items of the sequence which evaluates to False are removed. In simple words filter() method constructs an iterator from elements of an iterable for which a function returns true.
Example 1:-
numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,
11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 ]
def filter_numbers(num):
if num % 4 = = 0 :
return True
else :
return False
filtered_numbers = filter (filter_numbers, numbers)
filters = list (filtered_numbers)
print (filters)
|
Output:
[4, 8, 12, 16, 20]
Example 2:-
ages = [ 35 , 21 , 17 , 18 , 24 ,
32 , 50 , 59 , 26 , 6 , 14 ]
def Func(x):
if x < 20 :
return False
else :
return True
adults = filter (Func, ages)
for z in adults:
print (z)
|
Output:
35
21
24
32
50
59
26
Note: For more information, refer to filter() in python
Zipping and Unzipping
Zip()
is an inbuilt Python function that gives us an iterator of tuples. Zip is a kind of container that holds real data within. It takes iterable elements as an input and returns an iterator on them (an iterator of tuples). It evaluates the iterable from left to right. We can use the resulting iterator to quickly and efficiently solve common programming problems, like creating dictionaries. Unzipping is just the reverse process of zipping and for unzipping we use the * character with the zip()
function.
Example 1:-
a = ( "SHIVAM" , "SACHIN" , "VIKALP" , "RAGHAV" , "PRANAY" )
b = ( "SINGLA" , "SINGLA" , "GARG" , "GUPTA" , "GUPTA" )
x = zip (a, b)
print ( tuple (x))
|
Output:
((‘SHIVAM’, ‘SINGLA’), (‘SACHIN’, ‘SINGLA’), (‘VIKALP’, ‘GARG’), (‘RAGHAV’, ‘GUPTA’), (‘PRANAY’, ‘GUPTA’))
Example 2:-
name = [ 'sachin' , 'shivam' , 'vikalp' ]
age = [ 20 , 18 , 19 ]
result = zip (name, age)
result_list = list (result)
print (result_list)
n, a = zip ( * result_list)
print ( 'name =' , n)
print ( 'age =' , a)
|
Output:
[('sachin', 20), ('shivam', 18), ('vikalp', 19)]
name = ('sachin', 'shivam', 'vikalp')
age = (20, 18, 19)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...