8
>>> import functools as ft
>>> bk = ft.reduce(lambda x, y: x[0] + "." + y[0], ['alfa', 'bravo', 'charlie', 'delta'])
>>> bk
'a.d'
>>> km = ft.reduce(lambda x, y: x + y, [1, 2, 3, 4])
>>> km
10
>>> bk = ft.reduce(lambda x, y: x[0] + y[0], ['alfa', 'bravo', 'charlie', 'delta'])
>>> bk
'ad'
>>>

I expected something like 'a.b.c.d' or 'abcd'. Somehow, can't explain the results. There are similar questions here, but not quite like this one.

3 Answers 3

12

The result of executing the function passed as the first parameter, will be the first parameter to that function in the next iteration. So, your code works like this

lambda x, y: x[0] + "." + y[0]
  1. When x, y are 'alfa' and 'bravo' respectively, a.b.

  2. Now, x will be a.b and y will be 'charlie', so result will be a.c

  3. Now, x will be a.c and y will be 'delta', so result will be a.d

That is why the result is a.d

To get what you wanted, take all the first characters from all the strings to form a list and join all the elements together with ., like this

print(".".join([item[0] for item in data]))
# a.b.c.d

Note: I won't prefer this way, but for the sake of completeness, you can do it with reduce, like this

data = ['alfa', 'bravo', 'charlie', 'delta']
print(ft.reduce(lambda x, y: x + ("." if x else "") + y[0], data, ""))
# a.b.c.d

Now, the last empty string will be the first value for x in the first iteration. And we use . only if x is not an empty string otherwise we use an empty string, so that the concatenation would give the result you wanted.

3
  • 1
    '.'.join([item[0] for item in data]) - no need for building list in memory, better '.'.join(item[0] for item in data)
    – Ivan Klass
    Dec 12, 2014 at 9:32
  • 3
    @KlassIvan Yes, but building a list makes str.join run faster. Dec 12, 2014 at 10:39
  • I thought it's vice versa. Need to check
    – Ivan Klass
    Dec 12, 2014 at 10:59
5

If you want to use the reduce the most elegant way would be to do:

from functools import reduce
from operator import add

reduce(add, ['a', 'b', 'c']) # abc

Otherwise I think you better use the string.join interface:

''.join(['a', 'b', 'c']) # abc 
'.'.join(['a', 'b', 'c']) # a.b.c 
1

you could also use a list of the first characters and add the elements to get the same result here's an example using map:

list1 = ['alfa', 'bravo', 'charlie', 'delta']
from functools import reduce
print(reduce(lambda x,y:x+y,map(lambda x:x[0],list1)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.