Skip to content

Instantly share code, notes, and snippets.

@shivam5992
Created July 11, 2014 08:16
Show Gist options
  • Save shivam5992/98d4d2c90db47992ea09 to your computer and use it in GitHub Desktop.
Save shivam5992/98d4d2c90db47992ea09 to your computer and use it in GitHub Desktop.
use of lambda, filter, map and reduce in python
'''
Python script showing the use of lambda, map, reduce and filter keywords in Python
lambda: instantaneous, anonymous, use and throw function to be used at run time.
syntax: output = lambda arguments: express
map: Apply an expression over each element of list
filter: filtering out some elements out of a list based on a condition
reduce: reducing down list into a single element by applying a common expression
'''
import random
data = range(10)
random.shuffle(data)
''' map vs without map'''
data1 = [x*x for x in data]
data2 = map(lambda x: x*x, data )
''' filter vs without filter '''
data3 = filter(lambda x: x%2 != 0, data)
data4 = []
for x in data:
if x%2 != 0:
data4.append(x)
''' reduce vs without reduce '''
data5 = reduce(lambda x, y: x + y, data)
data6 = 0
for x in data:
data6 += x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment