Let's start with filter
In [ ]:
spam_eggs = "sPaM EggS"
print str.isupper
print filter(str.isupper, spam_eggs) # filter returns elements evaluated as True by first argument
In [ ]:
def my_filtering_func(input):
return input % 2 == 0
spam = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print filter(my_filtering_func, spam) # You can provide your own functions
In [ ]:
# It's time to use lambda
spam = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print filter(lambda x: x % 2 == 0, spam) # lambda keyword is used to create one-liner simple anonymous functions
In [ ]:
def get_power(y):
return lambda x: x ** y
cube = get_power(3)
print cube(2)
print cube(3)
In [ ]:
spam = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print map(lambda x: x ** 2, spam) # map applies the first argument function to all elements of iterable
In [ ]:
spam_eggs = "sPaM EggS"
print map(str.upper, spam_eggs) # map always returns a list
In [ ]:
eggs = (1, 2, 3, None, 5, 6, None, 8)
print map(None, eggs)
In [ ]:
print map(lambda x, y: x * y, spam_eggs, spam) # map can accept several iterables
In [ ]:
print map(lambda x, y: (y, x), "spam", spam) # map adds None in case one iterable has less elements
In [ ]:
# Let's check reduce
spam = [1, 2, 3]
print reduce(lambda x, y: x + y, spam) # reduce applies consecutively the function to each element of iterable
In [ ]:
spam = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print reduce(lambda x, y: x + y, spam) # reduce accumulates the result of each iteration
In [ ]:
spam = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print reduce(lambda x, y: x + y, spam, 1000) # Optionally reduce accepts an initializer as initial accumulated value
In [ ]:
# Let's continue with any and all
spam = [1, 2, 3, 4, 5]
print any(spam)
spam = [0, 1, 2, 3, 4, 5]
print any(spam)
spam = [None, 1, 2, 3, 4, 5]
print any(spam)
spam = []
print any(spam)
In [ ]:
spam = [1, 2, 3, 4, 5]
print all(spam)
spam = [0, 1, 2, 3, 4, 5]
print all(spam)
spam = [None, 1, 2, 3, 4, 5]
print all(spam)
spam = []
print all(spam)
In [ ]:
# enumerate
spam = "spam"
print list(enumerate(spam)) # Return an iterator of pairs (number, element) for elements in the iterable
In [ ]:
num = 0
spam = "spam"
for num, item in enumerate(spam, 1): # Useful in for loops
print item, "at index", num - 1
print "Number of items processed:", num
In [ ]:
# zip
spam = ['monday', 'tuesday',
'wednesday', 'thursday',
'friday']
eggs = [1, 2, 3, 4, 5]
fooo = ("MO", "TU", "WD",
"TH", "FR")
print zip(spam, eggs, fooo) # Return a list of tuples taking one element of each iterable at the same time
In [ ]:
spam = ['monday', 'tuesday',
'wednesday', 'thursday',
'friday']
eggs = [0, 1, 2, 3, 4,
5, 6, 7, 8, 9]
fooo = ("MO", "TU", "WD")
print zip(spam, eggs, fooo) # The resulting list is as long as the shortest input iterable
In [ ]:
# sum
spam = [1, 2, 3, 4, 5]
print sum(spam) # No explanation needed
print sum(spam, 100) # Optional second argument with initial sum value
In [ ]:
# range
print range(10) # Returns a list of numbers lower than provided value
print range(1, 10) # By default first number is 0, but you may specify it
print range(0, 10, 2) # You may also specify the step to increase
print range(0, -10, -2) # You may also specify negative values
In [ ]:
print xrange(0, 10, 2)
print list(xrange(0, 10, 2)) # It is a generator, no resources waste, no list created
In [ ]:
# sorted
spam = [2, 3, 1, 5, 4]
print sorted(spam) # Returns a new list with iterable content sorted
In [ ]:
spam = [2, 3, 1, 5, 4]
print sorted(spam, reverse=True) # Set reverse=True to get decremental sorting
In [ ]:
spam = ['monday', 'tuesday',
'wednesday', 'thursday',
'friday']
print sorted(spam, key=lambda x: len(x)) # You may provide a function to return a weight or comparison key
In [ ]:
spam = ['monday', 'tuesday',
'wednesday', 'thursday',
'friday']
print sorted(spam, cmp=lambda x, y: len(x) - len(y)) # Alternatively you may provide a function to compare pairs of elements
In [ ]:
# reversed
spam = [2, 3, 1, 5, 4]
print reversed(spam) # Returns an iterator. Only works with sequences, collections which have index access
print list(reversed(spam))
In [ ]:
sentences = ['Mary read a story to Sam and Isla.',
'Isla cuddled Sam.',
'Sam chortled.']
sam_count = 0
for sentence in sentences:
sam_count += sentence.count('Sam')
print sam_count
In [ ]:
sentences = ['Mary read a story to Sam and Isla.',
'Isla cuddled Sam.',
'Sam chortled.']
sam_count = reduce(lambda a, x: a + x.count('Sam'),
sentences,
0)
In [ ]:
# Imperative style: actions that change state from initial state to result
expr, res = "28+32+++32++39", 0
for t in expr.split("+"):
if t != "":
res += int(t)
print res
In [ ]:
# Functional style = apply transformation (and compositions)
from operator import add
expr = "28+32+++32++39"
print reduce(add, map(int, filter(bool, expr.split("+"))))