Advance Features of Python

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:-

filter_none

edit
close

play_arrow

link
brightness_4
code

# A simple generator function
def my_func():
    n = 1
    print('First Number')
    # Generator function contains yield statements
    yield n
  
    n += 1
    print('Second Number ')
    yield n
  
    n += 1
    print('Last Number ')
    yield n
  
# Using for loop
for number in my_func():
    print(number)    

chevron_right


Output:

First Number
1
Second Number 
2
Last Number 
3


Example 2:-

filter_none

edit
close

play_arrow

link
brightness_4
code

def str(my_str):
    length = len(my_str)
    for i in range(0, length ):
        yield my_str[i]
  
# For loop to print the string as 
# it is using generators and for loop.
for char in str("Shivam And Sachin"):
    print(char, end ="")

chevron_right


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:-

filter_none

edit
close

play_arrow

link
brightness_4
code

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()

chevron_right


Output:

Function requiring decoration.
Before executing function requiring decoration.
Function requiring decoration.
After executing requiring decoration.


Example 2:-

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

x = lambda a, b, c : a * b*c
print(x(5, 4, 3))

chevron_right


Output:

60

Example:- Code for adding 3 numbers.

filter_none

edit
close

play_arrow

link
brightness_4
code

x = lambda a, b, c : a + b+c
print(x(12, 40, 8))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

def func(n):
    return len(n)
  
a =('Singla', 'Shivam', 'Sachin')
x = map(func, a)
print(a)
  
# convert the map into a list,
#  for readability:
print(list(x))

chevron_right


Output:

('Singla', 'Shivam', 'Sachin')
[6, 6, 6]


Example:- Code to map number to its cube.

filter_none

edit
close

play_arrow

link
brightness_4
code

numbers = (1, 2, 3, 4)
res = map(lambda x: x * x*x, numbers)
  
# converting map object to list
numbersCube = list(res)
print(numbersCube)

chevron_right


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:-

filter_none

edit
close

play_arrow

link
brightness_4
code

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
          11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
  
# Function that filters out all 
# numbers which are multiple of 4
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)

chevron_right


Output:

[4, 8, 12, 16, 20]


Example 2:-

filter_none

edit
close

play_arrow

link
brightness_4
code

# To sort all ages which 
# are above 20 years
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)

chevron_right


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:-

filter_none

edit
close

play_arrow

link
brightness_4
code

# ZIPPING 
a = ("SHIVAM", "SACHIN", "VIKALP", "RAGHAV", "PRANAY")
b = ("SINGLA", "SINGLA", "GARG", "GUPTA", "GUPTA")
  
x = zip(a, b)
  
# use the tuple() function to display
#  a readable version of the result:
print(tuple(x))

chevron_right


Output:

((‘SHIVAM’, ‘SINGLA’), (‘SACHIN’, ‘SINGLA’), (‘VIKALP’, ‘GARG’), (‘RAGHAV’, ‘GUPTA’), (‘PRANAY’, ‘GUPTA’))

Example 2:-

filter_none

edit
close

play_arrow

link
brightness_4
code

# ZIPPING AND UNZIPPING
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)

chevron_right


Output:

[('sachin', 20), ('shivam', 18), ('vikalp', 19)]
name = ('sachin', 'shivam', 'vikalp')
age = (20, 18, 19)

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

I AM VERY MUCH PASSIONATE ABOUT CODING AND IMPROVING IT

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.