0

I am teaching myself python. I need to understand how the reduce function works. I have a solid understanding of how to use reduce for mathematical functions. However, I am trying to perform a more abstract operation to a list of integers and I encountered a problem.

Problem: I would like to take list like

digits= [3,4,3,2,1]

and unpack them such that I get

34421

Approach : I really cannot figure out how to create a lambda function that will extract the integer from the list. My approach is very bad and it is because I don't understand how to apply the function to the list. Also, I should note I am using python 3.

Example Code:

from functools import reduce
digits= [3,4,3,2,1]

reduce(lambda x : x, digits)
Evan Gertis
  • 1,796
  • 2
  • 25
  • 59

1 Answers1

1
>>> digits= [3,4,3,2,1]
>>> from functools import reduce
>>> reduce(lambda x,y:10*x+y,digits)
34321

Edit: Now the script returns an integer, credit to schwobaseggl.

kiyah
  • 1,502
  • 2
  • 18
  • 27
  • 1
    That is close to what I was trying to do, but I need to get an exact integer string. This is the dilemma. If this was c++ then it would be fairly trivial, but I would to implement this method in python – Evan Gertis Feb 08 '18 at 16:23
  • 1
    @EvanGertis Edited, now the code will return an integer – kiyah Feb 08 '18 at 22:41