This is my notes on some interesting python tips.

**Sort with Lambda**

As first, I would like to introduce how lambda can be used to sort the dictionary of word count (wc) based on the key or the value(name of the fruit and the count)

```
__author__ = 'ojitha'
wc ={'orange':2, 'mango':1, 'cherry':8, 'apple':5}
'''sort on key'''
print(sorted (wc.items(), key=lambda (word, count): word))
''' sort on the count'''
print(sorted (wc.items(), key=lambda (word, count): count))
```

The output of the above code is as follows

```
[('apple', 5), ('cherry', 8), ('mango', 1), ('orange', 2)]
[('mango', 1), ('orange', 2), ('apple', 5), ('cherry', 8)]
```

**List Comprehensions**

List of even and odds can be created as follows

```
listOfEvens = [x for x in range(10) if x %2 == 0]
print (listOfEvens)
listOfOdds = [x for x in range(10) if x %2 != 0]
print (listOfOdds)
```

The list comprehension is as follows

```
pairs = [(x,y) for x in range(5) for y in range(5)]
print(pairs)
```

This will create pairs as follows

`[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)`

**map function**

map function execute the function on sequence:

```
def multi(l,r):
return l * r
x = [1,2,3,4]
y = [10,20,30,40]
print(map(multi,x, y))
```

**filter function**

Here the filter which execute logical operation on sequence

```
def is_even(x):
return x % 2 == 0
x = [1,2,3,4,5,6,7,8,14,31,45]
print(filter(is_even, x))
```

**reduce function**

```
def multi(x, y): return x * y
x = [1,2,3,4]
print(reduce(multi, x))
```

pythonic way of enumeration

```
x = ['a','b','c','d']
for i, j in enumerate(x):
print i, j
```

zip and unzip

Here the example code to zip and unzip the lists

```
x = ['a','b','c','d']
y = [1,2,3,4]
z = ['p','q','r','s']
l = zip(x,y,z)
print l
p,q,r = zip(*l)
print p
print q
print r
```

Output as follows

```
[('a', 1, 'p'), ('b', 2, 'q'), ('c', 3, 'r'), ('d', 4, 's')]
('a', 'b', 'c', 'd')
(1, 2, 3, 4)
('p', 'q', 'r', 's')
```