Zip


In [2]:
x = [1, 2, 3]
y = [4, 5, 6]
z = [10, 12, 15, 17]

zip(x, y, z)


Out[2]:
[(1, 4, 10), (2, 5, 12), (3, 6, 15)]

In [3]:
a = [1, 2, 3, 4, 5]
b = [2, 2, 10, 1, 1]

for pair in zip(a,b):
    print max(pair)


2
2
10
4
5

In [4]:
# each iteration of a element here, which would be a tuple generated by
# zip(), gets evaluated with max() in order to return a single, large value. 
map(lambda pair: max(pair), zip(a,b))


Out[4]:
[2, 2, 10, 4, 5]

In [18]:
def switcharoo(d1, d2):
    dout = {}
    for k1, v2 in zip(d1, d2.itervalues()): #this zip creates the list of tuple ahead of time, and then iterates over it
        dout[k1] = v2
    return dout

In [19]:
dic1 = {'a':10, 'b':20}
dic2 = {'c':-20, 'd':-10}

switcharoo(dic1, dic2)


Out[19]:
{'a': -20, 'b': -10}

In [32]:
'''
todos:
1. wtf is sentinel = object() for? is it a common code design pattern 
2. why the * usage in parameter? is there reference/value aka, pointer, passing in python?
3. wtf is the yield reserved word do
'''
def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

Enumerate


In [21]:
l = ['a', 'b', 'c']
count = 0
for item in l:
    print count
    print item
    count += 1


0
a
1
b
2
c

In [22]:
for count,item in enumerate(l):
    print count, item


0 a
1 b
2 c

In [33]:
'''
Functionally equivalent def for enumerate built-in
'''
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

any() and all()


In [23]:
'''
Very simply: all() checks that all members of a list evalue to True whereas
any() check that at least 1 evaluates to true
'''

l_bool = [True, False, True, True]
any(l_bool)


Out[23]:
True

In [24]:
all(l_bool)


Out[24]:
False

In [30]:
is_weekend = True
is_vacation = False
is_before_noon = True
snooze_alarm_requirements = [is_weekend, is_vacation, is_before_noon]

if any(snooze_alarm_requirements):
    print("Snooze the alarm, it's too early")

if all(snooze_alarm_requirements):
    print("Come back later, ain't no body got time for this")
else:
    print("Really wished is was before noon, on a saturday on my vacation")


Snooze the alarm, it's too early
Really wished is was before noon, on a saturday on my vacation

In [34]:
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

In [ ]: