October 18

Advanced topic

List comprehension:
We have seen power of python programming, explaining one more powerful feature of Python. List comprehension provides a compact way of mapping a list to another list by applying user defined logic.

In the above example:

  • we have create a list [1,2,3,4,5,6,7]
  • using list comprehension we have created new list of odd integers
  • Note, list comprehension doesn’t change the original list
  • Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the variable

Lambda function:
Python provides very interesting one liner function which doesn’t have any name, called Lambda function.

  • Syntax of Lambda function is “lambda argument_list: expression”
  • multiple argument should be passed using comma separated
  • It doesn’t have return keyword

Filter function : This function take first argument as function and second argument will be sequence. Sequence will use the function and only those values will be captured which return True.

Map function : Map function takes two arguments, first argument is function and second one is sequence . you can pass single or multiple sequence.

Reduce function: Reduce function is different than map and filter, you must import reduce from the functools module explicitly. function reduce(f, seq) continually applies the function f() to the sequence seq and returns a single value.

Generator : In simple word,a generator looks like a function but behaves like an iterator. It has a yield keyword. a generator yields the values one at a time, which requires less memory. Lets generate Fibonacci series using generator function

Note :you can have multiple yield keyword in single function.

Decorator : Python decorator are wrapper of a function. They executed first then calling function get executed.
Let me take a small example to explain decorator, I need to print entry and exit time of function.

  • decorator denoted with @ symbol
  • first decorator function get called then main function get called