To wrap up our last 2 discussions about functions, namely how to use functions in Python and the temperature convertor, let us take a look at some functions that you may find useful in the future. We are going to start off easy and stack up. As before, we are going to be using Python 2.7. Before we get started let me remind every one, yes there are other ways, perhaps even better ways to code these functions. This is How I did it. It does not mean this is how you should do it. In fact, I would lover it if you left your version in the comments bellow! If you think it is too long for the comment section, send me an email and I will make it into a post. Lastly, these function are meant as an exercise, please be patient even if some of them do not make sense.

For each function (There are 22) we are going to look at the following:

1. Brief description of the function
2. Input types
3. Excepted output
4. Notes (if any)
5. Example execution
6. Code
7. Example Output for code
8. Final Notes (if any)

This is going to be long, so hang on. Let’s get started!

1. Even numbers:
Return a boolean value representing whether x is even or not.

input: number (integer)
output: True or False (boolean)

Example execution:
is_even(5) => False
is_even(42) => True

Code:

```def is_even(n):
return (n % 2) == 0
```

Code Output:

Final notes: Be aware the although the function is excepting an integer, a float might be passed in as the value of n. The result would always be False unless n is an even integer.

2. Remove evens:
Given a list of integers, remove all even values from the list and return an odd list of numbers.

input: a list of integers (list)
output: a list of odd numbers (list)

Example execution:
remove_evens([1,2,3,4,5,6]) => [1,3,5]

Code:

* Edited thanks to Eric Wilson (See comments)

```def remove_evens(alist):
res = []
for n in alist:
if not is_even(n): res.append(n)
return res
```

Code Output:

Final Note: You will notice that in this function we are calling another function within the module.

3. Min Value:
Accepts a list of numbers, and returns a copy of the smallest value in it.

input: a list if integers (list)
output: the minimum number (integer)

Example execution:
minval([104,22,31,4,54,61]) => 4

Code:

```def minval(alist):
return min(alist)
```

Code Output:

Final notes: Although in the input section we assumed that the function should only accept a list of integers. The function, as coded above, will also work for a mixed valued list. Python will use simple comparison to make sense and determine what the min value is.

Final notes 2: I am aware that that this function is useless since all it does is called the built in function min().

4. Index of Min Value:
Accepts a list of numbers, and returns the index (zero based) where the smallest value can be found. It must return the earliest index, in case of ties.

input: a list if integers (list)
output: the minimum number’s index in the list (integer)

Example execution:
min_index([104,22,31,4,54,61]) => 3

Code:

```def min_index(alist):
return alist.index(minval(alist))
```

Code Output:

Final Note: You will notice that in this function we are calling another function within the module.

5. Remove Value:
Finds the first instance of a value, and removes it from the list. Return a boolean, True when the value was removed, and False when the value wasn't found.

input: an integer value and a list of integer numbers
output: True or False (boolean)

Example execution:
remove_a_value(22,[104,22,31,4,54,61]) => True
remove_a_value(105,[104,22,31,4,54,61]) => False

Code:

```def remove_a_value(val, alist):
try:
alist.remove(val)
return True
except:
return False
```

Code Output:

6. Simple Sort:
Given a list of numbers, you will return a copy of the list with all elements in sorted (ascending) order. You must implement the following algorithm:

make a copy of the list make an empty result list
LOOP as long as the copylist isn't empty:
find the minimum value in the copylist, remove it
add that minval to the end of the resultlist return the result list

input: a list if integers (list)
output: a list of sorted integers (list)

Example execution:
simple_sort([104, 22, 31, 4, 54, 61]) => [4, 22, 31, 54, 61, 104]

Code:

```def simple_sort(alist):
copy = alist[:]
res = []
while len(copy) > 0:
x = minval(copy)
res.append(x)
copy.remove(x)
return res
```

Code Output:

Final Note: Although the function is assuming to work on integers, it may also work on other data types. Try it out.

7. Destructive Sort:
This behaves the same as Simple Sort, except that it must modify the original.

input: a list if integers (list)
output: NONE.

NOTE: In this function we will be modifying the original list, meaning it is a destructive function to the arguments passed in. Also note that the function does not have any return statements or a return value.

Example execution:
list_a = [33,94,1,92,54,12]
distraction_sort(list_a)

Code:

```#The code uses simple_sot(alist) to sort the list and then rewrites the original list values
def distraction_sort(xs):
temp = simple_sort(xs)
for i in range(len(temp)):
xs[i] = temp[i]
```

Code Output:

8. Middle Sort:
Without modifying the original list, find out what the middle element would be when all the elements are sorted. If the length is even (and thus no true 'middle' element), then out of the two elements closest to the middle, prefer the left one.

input: a list if integers (list)
output: the middle number if the list was sorted (an integer)

Example execution:
median_value([5,34,29,91,102,44,1,4]) => 29

Code:

```def median_value(xs):
temp = simple_sort(xs)
mid = int(len(xs)/2)
if is_even(len(xs)): mid -= 1
return temp[mid]
```

Code Output:

9. Kth Sorted:
Like Middle Sort, only we seek the Kth spot, not the middle spot. K is a zero-based integer index into the sorted version of list.

input: a list if integers (list)
output: the kth number if the list was sorted (an integer)

Example execution:
kth(2,[71,43,67,10,4,3,87,103s]) => 10

Code:

```def kth(k,xs):
temp = simple_sort(xs)
return temp[k]
```

Code Output:

10. Zip List:
Given two lists of values, create and return a list of tuples that "zip" up the values from the two lists together - first items in a pair, second items in a pair, and so on.

input: 2 lists of integers (lists)
output: a single list of tuples with values from both lists (a list)

Example execution:
zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']) => [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

Code:

```def zip(xs,ys):
res = []
i = 0
while i < len(xs) and i < len(ys):
res.append((xs[i],ys[i]))
i += 1
return res
```

Code Output:

11. Multiply Lists:
Given two lists of numbers, create a new list of numbers by multiplying the same-indexed values. As soon as one list runs out of values, the resulting list ends.

input: 2 lists of integers (lists)
output: a single list with the values from both list multiplied, while both lists have values (a list)

Example execution:
pairwise_multiply([2, 3, 10, 11], [35, 10, 29, 3]) => [70, 30, 290, 33]

Code:

```def pairwise_multiply(xs,ys):
res = []
i = 0
while i < len(xs) and i < len(ys):
res.append(xs[i]*ys[i])
i += 1
return res
```

Code Output:

12. Dot Product:
Given two lists of numbers, return a single number found by multiplying each same-indexed pair of numbers, and adding the results together.

input: 2 lists of integers (lists)
output: the sum of each pair of elements multiplied (an integer)

Example execution:
dot_product([1, 2, 3], [3, 2, 1]) => 10

Code:

```def dot_product(alist, blist):
return sum(pairwise_multiply(alist,blist))
```

Code Output:

13. N Copies:
Return a list with n copies of val.

input: a number and a value (integer,any)
output: a list with n copies of a given value (a list)

Example execution:
n_copy(5,3) => [5, 5, 5]

Code:

```def n_copy(val,n):
res = []
for i in range(n):
res.append(val)
return res
```

Code Output:

14. Interleave:
Given two lists of values, create (and return) the interleaved version by making a new list with the first value of list_a, then the first value of list_b, then the second value of list_a, second value of list_b, and so on. Once a list is done the rest of the values from the other list are added to the resulting list.

input: 2 lists of integers (lists)
output: A single list with the values from both lists interleaved (a list)

NOTE: Etra valuees for either list are added to the end of the result list

Example execution:
interleave(['a', 'b', 'c'], [1, 2, 3]) => ['a', 1, 'b', 2, 'c', 3]

Code:

```def interleave(alist,blist):
res = []
i = 0
while i<len(alist) and i<len(blist):
res.append(alist[i])
res.append(blist[i])
i += 1
for j in range(i,len(alist)):
res.append(alist[j])
for j in range(i,len(blist)):
res.append(blist[j])
return res
```

Code Output:

15. Riffle Shuffle:
Imagine we were shuffling cards with the standard "riffle" shuffle (just interleaving two halves of the deck together). For many card games, we need to perform multiple shuffling in order to get enough apparent randomness in the order of cards. List represents the 'deck' to be shuffled, and n represents how many "riffle" shuffling need to be performed.

input: a single list (a list)
output: a shuffled list (a list)

NOTE: Like function 7, distraction_sort, this function modifies the original values given

Example execution:
list_a = ['a','b','c','d','e','f','g']
riffle_shuffle(list_a)

Code:

```def riffle_shuffle(alist):
temp = alist
mid = int(len(alist)/2)
temp = interleave(temp[0:mid],temp[mid:len(alist)])
for i in range(len(alist)):
alist[i] = temp[i]
```

Code Output:

16. Pairs:
Create and return a list of all possible pairs from values in list_a and values in list_b. The order of elements is important! all of the pairs of list_a first element must appear before all pairs involving list_a second element; similarly, when pairing with a specific element from list_a, these pairs must include list_b elements in the same order as original.

input: 2 lists of integers (lists)
output: a single list with pairs of values from both lists (a list)

Example execution:
all_pairs([1, 2, 3], ['a', 'b', 'c']) => [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]

Code:

```def all_pairs(alist,blist):
res = []
for x in alist:
for y in blist:
res.append((x,y))
return res
```

Code Output:

17. Build Deck:
Create a fresh, organized deck. You must generate the result from these two strings: one representing all the pips (card values) "23456789TJQKA", and another representing the suits, "CDHS".

input: 2 strings, “23456789TJQKA” and “CDHS” (strings)
output: a list of cards (a list)

NOTE: each card will be repressed by a value and suit. For example: 4C is 4 of clubs, TS is ten of spades and QH is queen of heats.

Example execution:
new_deck()

Code:

```def new_deck():
val = "23456789TJQKA"
shapes = "CDHS"
return (all_pairs(val,shapes))
```

Code Output:

18. Reduce Dimension:
Given a list of more than one dimension, create and return a new list by collapsing that outermost dimension.

input: a multidimensional list (a list)
output: the list without the outmost dimension (a list)

NOTE: This function only reduces the original list dimension by 1, not a full flatten.

Example execution:
flatten([[[1, 2, 3], 4], [5]]) => [[1, 2, 3], 4, 5]

Code:

```def flatten(alist):
res = []
for i in alist:
for j in i:
res.append(j)
return res
```

Code Output:

19. Map:
Given a python function and a sequence of values, create and return a new list by calling the function on each value in the sequence and placing the results into the returned list.

input: a function name and a sequence of values (string,tuple/list)
output: the results from the mapped function onto the sequence of values (a list)

Example execution:
map(ord,”Hello World”) => [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

Code:

```def map(f,alist):
res = []
for x in alist:
res.append(eval(str(f(x))))
return res
```

Code Output:

20. Zip With:
Combine elements of list_a and list_b together while using the operator, generating a new list.

input: a function and 2 lists (string,lists)
output: a list with the values from applying the function on the lists values (a list)

Example execution:
zip_with(add, [1, 2, 3], [4, 5, 6]) => [5, 7, 9]

Code:

```def zip_with(f,alist,blist):
res = []
i = 0
while i<len(alist) and i<len(blist):
res.append(eval(str(f(alist[i],blist[i]))))
i += 1
return res
```

Code Output:

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

#### You Might Also Like

• serverhorror

>>> import itertools
>>> help(itertools)

God point. However, what o you do if you don't have the built-in?

• serverhorror

Depends on what you consider 'built-in'. itertools has been there since 2.3 (http://docs.python.org/release/2.3.5/lib/itertools-functions.html). Granted there are probably quite a few functions that are new between 2.3 and 3.4.

I tend to think of it that way:

* run on 2.7 if absolutely necessary
* run on 3 if somehow possible

I sincerely hope you are not referring to an artificially crippled version of Python that doesn't have the itertools module...

I have the need to code in some environments that import became an issue. However, you are correct, most likely there will be access to itertools. Beside, some languages do not have fancy built in like Python. What would you do if you had to o this in C? Knowing what goes on and how things are implemented is sometimes a big plus.

• serverhorror

> Beside, some languages do not have fancy built in like Python.

err.... so why not provide samples in languages where you actually need it, instead of posting stuff that mostly makes code less readable?

What part of the code do you not find readable?

• flowing

Exactly...

• TheBlackCat13

Is there a reason you don't want to use sorted and [].sort for 6 and 7?

Assumed we don't use itertools (which makes many of these even easier):

For 8, I would just do:
return sorted(xs)[(len(xs)-1)//2]

or
mid = (len(xs)-1)//2
return sorted(xs)[mid]

I am not sure why 10 exists when there is a built-in zip function.

for 11 I would do:
return [x*y for x, y in zip(list1, list2)]

For 13 I would just do:
return [val]*n

For 14, I would:
return list(sum(zip(alist, blist), ()))

For 15, I would use the same "mid" approach as I did for my version of 8

For 16, that would work, but itertools.product is easier. It can also be done in a list comprehension:
sum([[(x, y) for y in blist] for x in alist], [])

For 18, I have already used this several times:
return sum(alist, [])

But it is easier with itertools.chain

For 19, if I wasn't using the built-in map I would use a list comprehension:
return [f(x) for x in alist]

For 20 I would do the same:
return [f(x, y) for x, y in zip(alist, blist)]

For 6 it is practice implementing an algorithm + trying to avoid built-in help. For 7 it is to point out the Python function can overwrite the argument original values For 10 it does, as serverhorror pointed out
For 8, 11, 13,14,15,16,17,18,19 and 20, I agree, you solutions could work as a 1 line function.
Thank you for taking he time and showing another way to do things!

• Liu Bo

I just check 19, you doing it totally wrong, no one would do it like that in Python. Your post may has good format and great idea, but you need to deep into Python more.

• David Lawrence

Wanting to practice implementing algorithms is a good way to spend your time, but that shouldn't be presented under the title "20 good functions to know in python". It is much better that developers knows to use the heavily optimized sorted() function than to re-implement a (significantly less efficient) sorting algorithm on their own.

The danger with articles like this is that some new developer reads the article, doesn't read the comments, and starts doing bad things in their code. I'm continuously surprised by the number of interviewees I speak to that aren't aware of itertools or collections, let alone the built in functions.

• Eric Wilson

The remove_evens function does not work. Try it on [1,2,2,3,4,4,4] and you may come to understand when you shouldn't mutate a list as you are iterating through it.

You are correct! Thanks. Please see updated code.

• http://orderofsql.wordpress.com/ Scott Edwards

Hi, @CptDeadBones, glad you corrected the code, but I'm really curious what the issue was. I'm guessing it's a common error that Eric is referring to. Is there any way to see the original version of the function? Either on Github or perhaps you could paste here in comment? Thanks!

• Ram Sharma

alist.remove(n) is the bug .... which makes the function "remove_evens" not work correctly ...
input :
allevenList = [2,4,5,6,7,8,2,6,8,9]
output : [4, 5, 7, 2, 8, 9]

Correct. Code has been updated.

• cborgolte

Why would one want to write functions around oneliners?

Ore even worse: your minval() function is nothing than returning the standard library's min() function! What is that good for? If you dont like the name, it would be shorter to write minval=min 😉

Finding even numbers in a list:
[val vor val in lst if val % 2 == 0]
Thats one line, readable by any midlevel Python programmer. No need to put this in an own function.

Riffle shuffle:

list(itertools.chain(*zip(alist[:len(alist)/2], alist[len(alist)/2:])))

...

I am not sure what [val vor val in lst if val % 2 == 0] means. I have never seen Python written like that.

You one liner Riffle Shuffle is impressive, but incorrect. For the input ['a','b','c','d','e','f','g'] it outputs ['a', 'd', 'b', 'e', 'c', 'f']. Where is the 'g'?

• flowing

Is this a joke? L.index(min(L)) for example means you need to traverse L twice. How did this junk make it onto the Python mailing list?

Very good question. I am not sure how this ended up the Python Mailing list. Still, I think it is valid. Do you have a better idea? We would love to hear it.

• flowing

How about storing the index/offset together with the min value? And, ask your CP0101 teacher for more information... Sorry for being so harsh, but this stuff is really basic, any old "Python Cookbook" will have better solutions for your examples than what you've shown us here [see @serverhorror:disqus ].

• Dg

Why not?

• Andrey

Achtung! PHP programmers everywhere!

• alternate

Worst article i have ever seen. Code is so bad, so the title should be '20 bad functions in python', ugh!

• FrancisGan

Don't give up. Just do your best. Keep improving. Keep the good work

Thanks! You too.

• FrancisGan

Thanks also to all who contributed positively

• Stephen Paul Chappell

Much of your code could be rewritten to shorter and more powerful. In several cases, you could use what is already built into the language or standard library. If you are not sure about something, remember that StackOverflow is your friend.

# 1. Even Numbers:
is_even = lambda n: not n & 1
# 2. Remove Evens:
remove_evens = lambda iterable: (n for n in iterable if n & 1)
# 3. Min Value:
minval = min
# 4. Index of Min Value:
min_index = lambda iterable: min((n, i) for i, n in enumerate(iterable))[1]
# 5. Remove Value (alternate):
remove_a_value = lambda val, iterable: (v for v in iterable if v != val)
# 6. Simple Sort:
simple_sort = sorted
# 7. Destructive Sort:
destructive_sort = list.sort
# 8. Middle Sort:
import statistics
median_value = statistics.median
# 9. Kth Sorted:
import heapq
kth = lambda k, iterable: heapq.nsmallest(k + 1, iterable)[-1]
# 10. Zip Lists:
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)
# 11. Multiply Lists:
pairwise_multiply = lambda x, y: (a * b for a, b in zip(x, y))
# 12. Dog Product:
dot_product = lambda x, y: sum(pairwise_multiply(x, y))
# 13. N Copies:
n_copy = lambda val, n: [val] * n
# 14. Interleave (alternate):
interleave = lambda *iterables: (i for t in zip(*iterables) for i in t)
# 15. Riffle Shuffle (inverse):
riffle_shuffle = lambda iterable: iterable[0::2] + iterable[1::2]
# 16. Pairs:
all_pairs = lambda x, y: ((a, b) for a in x for b in y)
# 17. Build Deck:
new_deck = lambda: all_pairs('23456789TJQKA', 'CDHS')
# 18. Reduce Dimension:
flatten = lambda iterable: (j for i in iterable for j in i)
# 19. Map
map = lambda f, iterable: (f(x) for x in iterable)
# 20. Zip With:
zip_with = lambda f, *iterables: (f(*args) for args in zip(*iterables))