1

I am trying to learn the functional programming way of doing things in python. I am trying to serialize a list of strings in python using the following code

S = ["geeks", "are", "awesome"]
reduce(lambda x, y: (str(len(x)) + '~' + x) + (str(len(y)) +  '~' + y), S)

I am expecting:

5~geeks3~are7~awesome

But I am seeing:

12~5~geeks3~are7~awesome

Can someone point out why? Thanks in advance!

4 Answers 4

2

reduce function on each current iteration relies on previous item/calculation (the nature of all reduce routines), that's why you got 12 at the start of the resulting string: on the 1st pass the item was 5~geeks3~are with length 12 and that was used/prepended on next iteration.

Instead, you can go with simple consecutive approach:

lst = ["geeks", "are", "awesome"]
res = ''.join('{}~{}'.format(str(len(s)), s) for s in lst)
print(res)    # 5~geeks3~are7~awesome
Sign up to request clarification or add additional context in comments.

Comments

1

You need to add the initializer parameter - an empty string to the reduce() function. It will be the first argument passed to the lambda function before the values from the list.

from functools import reduce

S = ["geeks", "are", "awesome"]

reduce(lambda x, y: x + f'{len(y)}~{y}', S, '')
# 5~geeks3~are7~awesome

Equivalent to:

((('' + '5~geeks') + '3~are') + '7~awesome')
# 5~geeks3~are7~awesome

Comments

1

The reduce function is for aggregation. What you're trying to do is mapping instead.

You can use the map function for the purpose:

''.join(map(lambda x: str(len(x)) + '~' + x, S))

This returns:

5~geeks3~are7~awesome

Comments

1
  • here is the solution for pyton3.7+ using fstring.
>>> S = ["geeks", "are", "awesome"]
>>> ''.join(f'{len(s)}~{s}' for s in S)
'5~geeks3~are7~awesome'

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.