0

Can someone explain the structure of reduce() in the following example:

def f2(list):
        return reduce(lambda string, item: string + chr(item), list, "")

I know that f2 converts a list of int's into a string, but my problem is understanding reduce in this context. I know the basic structure of reduce is reduce(function, sequence[, initial]) but this is somehow confusing to me. Can someone explain reduce(lambda string, item: string + chr(item), list, "") and give me some similar examples ? Thanks in advance.

Mite Ristovski
  • 231
  • 4
  • 9
  • 2
    Note that some of the `builtins` and `modules` are used as names in this code, such as `list` and `string`, this is not good practice. Also don't worry too much about `reduce` because usually there is a better way of doing something without using `reduce`. – jamylak May 03 '12 at 10:14
  • 3
    This is more properly written `"".join(map(chr, list))`. – Fred Foo May 03 '12 at 10:14

3 Answers3

3
return reduce(lambda string, item: string + chr(item), list, "")

roughly translates to

string = ""
for item in list:
    string = string + chr(item)
return string
vartec
  • 131,205
  • 36
  • 218
  • 244
3

Reduce does something usually called a fold. E.g., if you have a list ls = [a,b,c,d] and a binary operation def plus(x,y): x + y, then reduce(plus, ls) gets folded to

plus(plus(plus(a, b), c), d)

which equals

(((a+b)+c)+d)

Your f2 is doing something similar, namely appending strings (after converting them from integers): (I really hope those parens match...)

(((("" + chr(a)) + chr(b)) + chr(c)) + chr(d))

with a supplied initial value of "" (which is needed when a folding operation has two different input types)

@ python experts: I'm not sure if reduce is a left fold, it seemed more naturally to me. Please tell me if I'm wrong.

phipsgabler
  • 20,535
  • 4
  • 40
  • 60
2

The code applies chr() to every element of the list, and concatenates the results into a single string.

The reduce() call is equivalent to the following:

return "" + chr(list[0]) + chr(list[1]) + ... + chr(list[list.length - 1])

The "" is the third argument to reduce(). The lambda function in

return reduce(lambda string, item: string + chr(item), list, "")

is called for every item in the list. It simply appends chr(item) to the result of the previous iteration.

For more examples of using reduce(), see Useful code which uses reduce() in python

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012