Skip to content

Instantly share code, notes, and snippets.

@bikz05
Created December 4, 2014 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bikz05/eabb0a730bf47d1654d0 to your computer and use it in GitHub Desktop.
Save bikz05/eabb0a730bf47d1654d0 to your computer and use it in GitHub Desktop.
Python Idioms
# zip([iterable, ...])
# This function returns a list of tuples,
# where the i-th tuple contains the i-th
# element from each of the argument sequ-
# ences or iterables.
a = [1, 2, 3, 4, 5, 6];
b = [6, 5, 4, 3, 2, 1];
c = [cA*cB for cA, cB in zip(a, b)]; # c = [6, 10, 12, 12, 10, 6]
# Sorting using keys
# More at https://wiki.python.org/moin/HowTo/Sorting
d = [-2, -23, 32, -3, 0, -34];
print sorted(d, key = lambda x:abs(x), reverse = True);
# OUTPUT = [-34, 32, -23, -3, -2, 0]
# map(function, iterable, ...)
# Apply function to every item of iterable
# and return a list of the results.
print map(hash, b); # This will hash all the ints in b
# lambda - creating anonymous inline functions
print (lambda x, y: x*y)(3, 4); # OUTPUT = 4
incrementer = lambda input: input + 1;
# above is same as def incrementer(input): return input+1
# now we call it
print incrementer(3); # OUTPUT = 12
# lambda and map together
squares = map(lambda x: x**2, range(10));
print squares # OUTPUT = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# filter
# Filter takes a function returning True or False and applies
# it to a sequence, returning a list of only those members of
# the sequence for which the function returned True.
special_squares = filter(lambda x: x > 5 and x < 50, squares);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment