Some Cool Single-Line Functions in Python

Recently did many exercises with Python. I have to say it’s really a beautiful language! Lots of cool stuff could be achieved with a single-line function.

Here are some examples. I will add more when I come across them. Please add comments if you think there’s even a better way!

1. Write a function that takes a list, and returns a dictionary with keys the elements of the list and as value the number of occurances of that element in the list:

def count_list(l): return { key: l.count(key) for key in l }

2. Reverse look-up: Write a function that takes a dictionary and a value, and returns the key associated with this value.

def reverse_map(dict, v): return {value: key for key, value in dict.items()}[v]

3. Print the numbers 1 to 100 that are divisible by 5 but not by 3:

Method 1:

x1=range(101)

print filter(lambda x1: x1 % 5 == 0 and x1 % 3 != 0, x1)

Method 2:

[i for i in range(101) if i%5==0 and i%3!=0]

4. Loop over elements and indexes of a list, print them in a given form:

myList=[1, 2, 4]

for index, elem in enumerate(myList): print ‘{0} ) {1}’.format(index, elem)

result:

0) 1

1) 2

2) 4

5. Nearest neighbor – Write a function that takes a value z and an array A and finds the element in A that is closest to z. The function should return the closest value, not index

def find_nearest(a, a0):

return a.flat[np.abs(a – a0).argmin()]

**More to come!

Leave a comment