Python (Chapter 5.3) : Advanced features of LIST


For any type of consultation, query or doubt. You may contact to the following: (+91) 9804 436 193 debabrataguha20@gmail.com 
and join the group  https://www.facebook.com/groups/331231161093613/




Part 1: LAMBDA FUNCTIONS

Purpose or the Usage of Lambda function is similar to a Function or method. Anyone who does not know FUNCTION or METHOD skip the following code:

def func(a):
    print (a*a)
func (2)
func (3)
func (4)

Output:

4
9
16


In Lambda Function, our purpose is the same. To reuse the code , instead of writing the same code for different values again and again. First we will try to learn the syntax of using LAMBDA function. It does not require any prior knowledge on methods/functions.


Example 1:
func = lambda x : x*x
print ( func(2) )
print ( func(3) )
print ( func(4) )

Output:

4
9
16




There are 3 parts of a LAMBDA function.

Part 1: “ func = “

“func” is the function name, We can call the python code by this name “func” again and again.


Part 2: “ lambda x ”

      variables mentioned after the word  lambda” will be the parameter given by user. Different values given by users will be entered into the code as “x”.


Part 3: “ : x * x ”

               The python logic written after the colon (“:”) will be returned. In the above program, if we have entered 2 as x, it will return x*x means 4.









For the simple logics like to print the square value of a number, you will not be able to understand the meaning of “Reusing code”. But you will be able to know the meaning when I will write the logic to print the Fahrenheit temp into celcius.

Example 2:

func=lambda x: 5*(x-32)/9
print (func(-40))
print (func(212))
print (func(32))

Output:
-40
100
0








We can use multiple parameters like x,y ..

Example 3:
func=lambda x,y : x*x + y*y
print (func(2,3))
print (func(5,6))
print (func(-6,7))

Output:
13
61
85








Part 2: LAMBDA FUNCTIONS WITH MAP

Map is being used to perform a calculation with the help of a set of values or multiple set of values.

The basic structure of map is like below:

map ( lambda x: x*x , ListName )

or in simple words,

map(function_object, iterable1, iterable2,...)




Now we will repeat example 2 for a set of values kept in a list

Using map function, we can convert all the values of the list “Temp” and store into “Temp2”.


Example 3:
temp = [ -40, 212, 32]
temp2 = list( map ( lambda x: 5*(x-32)/9 , temp))
print ( temp2 )

Output:
[ -40 , 100, 0 ]

              



Example 4:
arr1=[100,200,300,400]
result=list(map(lambda x: x*x , arr1))
print(result)

Output:
[ 10000 , 40000, 90000 , 160000 ]

              




We can use multiple parameters like x,y .. but the parameters will be taken from different lists.

Example 5:
arr1=[100,200,300,400]
arr2=[10,20,30,40]
result=list(map(lambda x,y : x*x + y*y , arr1 , arr2))
print(result)

Output:
[ 10100 , 40400, 90900 , 161600 ]

              



Example 6:
arr1=[100,200,300,400]
arr2=[10,20,30,40]
arr3=[1,2,3,4]

result=list(map(lambda x,y,z : x*x + y*y + z*z , arr1 , arr2 , arr3))
print(result)

Output:
[ 10101 , 40404, 90909 , 161616 ]

              





We can even directly use a list in the map function in following manner.

Example 7:
arr1=[100,200,300,400]
arr2=[10,20,30,40]

result=list(map(lambda x,y,z : x*x + y*y + z*z , arr1 , arr2 , [1,2,3,4]))
print(result)

Output:
[ 10101 , 40404, 90909 , 161616 ]










We can even use the lists having uneven elements inside. It will calculate the term as per the shortest list then. Please check the below program. It will be easy to understand. Arr3 is having only 3 elements. So the final answer is also for 3 elements only

Example 8:
arr1=[100,200,300,400]
arr2=[10,20,30,40]
arr3=[1,2,3]

result=list(map(lambda x,y,z : x*x + y*y + z*z , arr1 , arr2 , arr3))
print(result)

Output:
[ 10101 , 40404, 90909 ]







Part 3: LAMBDA FUNCTIONS WITH FILTER

Filter is being used to choose some values from a set of values on some criteria or condition.

The basic structure of FILTER is like below:

filter ( lambda x: x%2 == 0 , ListName )

or in simple words,

filter (function_object, iterable1, iterable2,...)





Example 9:
arr1=[10,20,30,40,50]
result=list(filter(lambda x : x % 4 ==0 , arr1 ))
print(result)

Output:
[ 20, 40 ]

              





Example 10:
arr1=[10,20,30,40,50]
result=list(filter(lambda x : x % 4 != 0 , arr1 ))
print(result)

Output:
[ 10, 30, 50 ]

              






We can remove  “!=” from the criteria. It will be same like not equals to. Please the following program.

Example 11:
arr1=[10,20,30,40,50]
result=list(filter(lambda x : x % 4 , arr1 ))
print(result)

Output:
[ 10, 30, 50 ]

              







We can also use IN function with FILTER function.

Example 12:
arr1=[10,20,30,40,50]
arr2=[10,30,60,70,80]
result=list(filter(lambda x : x in arr1, arr2 ))
print(result)

Output:

              





We can also use IN RANGE function with FILTER function.

Example 13:
arr1=[10,20,30,40,50]
result=list(filter(lambda x : x in range(30) , arr1 ))
print(result)

Output:
[ 10, 20 ]

              





Part 4: LAMBDA FUNCTIONS WITH REDUCE

REDUCE function is being used to perform a function repeatedly through all the elements of the list.

The basic structure of REDUCE is like below:

reduce ( lambda x,y: x + y , ListName )

or in simple words,

filter (function_object, iterable)

One point is to be notified here is that REDUCE is available under “functool” package.







Example 14:
import functools
lst= [10,20,30,40,50]
print ( functools.reduce ( lambda x,y: x + y , lst ) )

Output:
150

What it does is to add 10 (1st term) and 20 (2nd term) and the answer become 30
Then 30 (sum) + 30 (3rd term) =60
Then 60 (sum) + 40 (4th term) =100
Then 100 (sum) + 50 (5th term) = 150







Example 15:
import functools
# finding maximum

lst= [10,20,30,40,50]
print ( functools.reduce(lambda x,y : x if x > y else y , lst ))

Output:
50







We can use a range of numbers instead of a list

Example 16:

import functools
# finding maximum

print ( functools.reduce ( lambda x,y : x if x > y else y , range(1,30) ) )

Output:
29

              







Example 17:

import functools
# finding maximum

print ( functools.reduce ( lambda x,y : x if x > y else y , range(1,30) ) )

Output:
29

              








Example 18:

import functools
# finding (1 + 2 + 3 + … + 29) / ( 1 * 2 * 3 * 4 )

print ( functools.reduce ( lambda x,y : x + y , range(1,30) ) / functools.reduce ( lambda x,y : x * y , range(1,5) ) )

Output:
18.125





              



Part 5: LIST USING SET

We can use some short cut using the set theory of mathematics. If you do not know anything about Set theory, no need to worry. See the basic operations of set as below.

1.      We can easily convert a list into a set. Both are having a similar type of look.

lst=[10,20,30,40,50]
st = set (lst)
print (st)

      Output:
                  { 10 , 20, 30, 40, 50 }


2.      We can easily extract the intersection of the lists

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)

print ( st1 & st2 )
print (list(st1 & st2))

Output:
                  { 40, 50 }
                  [ 40, 50 ]


               Alternatively we can use .intersection() method as well.

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)

print ( st1.intersection( st2 ) )
print (list(st1.intersection( st2 )))

Output:
                  { 40, 50 }
                  [ 40, 50 ]


3.      We can easily extract the union of the lists

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)

print ( st1 | st2 )
print (list(st1 | st2))

Output:
                  {10, 20, 30, 40, 50, 60}
                  [10, 20, 30, 40, 50, 60]


               Alternatively we can use .union() method as well.

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)

print ( st1.union( st2 ) )
print (list(st1.union( st2 )))

Output:
                  {10, 20, 30, 40, 50, 60}
                  [10, 20, 30, 40, 50, 60]




4.      We can even do this for multiple number of lists

lst1=[10,20,30,40,50]
lst2=[40,50,60]
lst3=[90,100]
st1 = set (lst1)
st2 = set (lst2)
st3 = set (lst3)

print ( st1 | st2 | st3 )
print (list(st1 | st2 | st3 ))

Output:
                  {10, 20, 30, 40, 50, 60 , 90 , 100 }
                  [10, 20, 30, 40, 50, 60 , 90 , 100 ]




5.      We can easily do set1-set2

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)
print ( st1 - st2 )
print (list(st1 - st2))

Output:
                  {10, 20, 30}
                  [10, 20, 30]

               Alternatively we can use .difference() function.

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)
print ( st1.difference(st2) )
print (list(st1.difference(st2)))

Output:
                  {10, 20, 30}
                  [10, 20, 30]




6.      We can easily extract the union of the lists

lst1=[10,20,30,40,50]
lst2=[40,50,60]
st1 = set (lst1)
st2 = set (lst2)
print ( st1 | st2 )
print (list(st1 | st2))

Output:
                  {10, 20, 30, 40, 50, 60 , 70}
                  [10, 20, 30, 40, 50, 60 , 70]





Part 6: LIST with Zip:

The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.

1.      Sort 1st list using the 2nd one:

a.      Zip the two lists.
b.     Create a new, sorted list based on the zip using sorted().
c.      Using a list comprehension extract the first elements of each pair from the sorted, zipped list.

x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] 
y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1] 
zipped_pairs = zip(list2, list1) 
      z = [x for _, x in sorted(zipped_pairs)]   
print ( z ) 

Output:

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
['g', 'k', 'r', 'e', 'e', 'g', 's', 'f', 'o']



2.      Print 3 list simultaneously.

num = [1, 2, 3] 
color = ['red', 'while', 'black'] 
value = [255, 256]

for (a, b, c) in zip(num, color, value): 
     print (a, b, c)

               Output:

               1             red         255
               2             white    256

Only 2 rows have been printed due to the length of third list is 2.





3.      itertools.zip_longest() : zip_longest stops when all lists are exhausted. When the shorter iterator(s) are exhausted, zip_longest yields a tuple with None value. Below is an implementation of the itertools.zip_longest which iterates over 3 lists:

num = [1, 2, 3] 
color = ['red', 'while', 'black'] 
value = [255, 256]

for (a, b, c) in itertools.zip_longest(num, color, value): 
     print (a, b, c)

               Output:
               1             red         255
               2             white     256
               3                      black     none



4.      We can also specify a default  value instead of NONE in zip_longest()

num = [1, 2, 3] 
color = ['red', 'while', 'black'] 
value = [255, 256] 

for (a, b, c) in itertools.zip_longest(num, color, value, fillvalue=-1): 
print (a, b, c)

               Output:

               1             red         255
               2             white    256
               3             black     -1


Comments

Popular posts from this blog

Java concepts Theory

About Myself ..