Tricks and tricks with lists

Python Lists are a flexible container that holds other objects

  • lambda - shorthand to create an anonymous function
  • zip - take iterables and zip them into tuples
  • map - applies a function over an iterable

In [55]:
x = [1,2,3]
lambda x: max(x)


Out[55]:
<function __main__.<lambda>>

Simple list comprehensions


In [56]:
a = range(-5,5)

## with builtins
b = map(abs,a)
c = [abs(x) for x in a]
print b==c,b

## with your own function
b = [x**2 for x in a]
print b==c,b


True [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
True [25, 16, 9, 4, 1, 0, 1, 4, 9, 16]

Filtering list comprehensions


In [57]:
import types

## filter
a = ['', 'fee', '', '', '', 'fi', '', '', '', '', 'foo', '', '', '', '', '', 'fum']
b = filter(lambda x: len(x) > 0,a)
c = [x for x in a if len(x) > 0]
print b==c,b

## square only the ints and filter the rest                                                                                                                                                                           
a = [1, '4', 9, 'a', 0, 4]
b = [ x**2 for x in a if type(x)==types.IntType ]
c = map(lambda x: x**2, filter(lambda x: isinstance(x,int) == True,a))
print b==c,b


True ['fee', 'fi', 'foo', 'fum']
True [1, 81, 0, 16]

Nested list comprehensions


In [ ]:
a = [1, 2, 3, 4]
[elem*2 for elem in
 [item+1 for item in li] ]

Having fun with Zip


In [58]:
a1,a2 = [1,2,3],['a','b','c']
print zip(a1,a2)    
print zip(*[a1,a2])


[(1, 'a'), (2, 'b'), (3, 'c')]
[(1, 'a'), (2, 'b'), (3, 'c')]

In [59]:
dict(zip(a2,a1))


Out[59]:
{'a': 1, 'b': 2, 'c': 3}

In [60]:
## transpose
a = [[1,2,3],[4,5,6]]
print(a)
b = map(list, zip(*a))
c = [[row[i] for row in a] for i in range(len(a[0]))]
print b==c,b

## rotate (to the right 90 degrees)
b = map(list, zip(*a[::-1]))
c = [[row[i] for row in a[::-1]] for i in range(len(a[0]))]
print b==c,b


[[1, 2, 3], [4, 5, 6]]
True [[1, 4], [2, 5], [3, 6]]
True [[4, 1], [5, 2], [6, 3]]

In [63]:
## Are list comprehensions always easier?
b = map(lambda x: max(x), zip(*a))

## what is the equivalent list comprehension?
c =[max(tpl) for tpl in [[row[i] for row in a] for i in range(len(a[0]))]]
print b==c,b


True [4, 5, 6]

In [ ]: