Reputation: 1149
I am trying to understand the process of Reduce in Python by running the following commands in Colab Notebook :
pList20 = ["Ram", "RamPM", "Shyam", "PMShyam", "Sita", "SiPMMta"]
print(pList20)
pList21A = list(map(lambda x : (x,len(x)),pList20) ) # returns a list of tuples
print(pList21A)
pList21B = list(map(lambda x : (len(x),x),pList20) ) # returns a list of tuples
print(pList21B)
print('----')
print(pList21A)
pVal22A = functools.reduce(lambda x,y: (x[0]+y[0], x[1]+y[1]), pList21A) # adding and concatenating elements in a list
print(pVal22A)
print(pList21B)
pVal22B = functools.reduce(lambda x,y: (x[0]+y[0], x[1]+y[1]), pList21B) # adding and concatenating elements in a list
print(pVal22B)
print('----')
#print(pList21A)
#pVal22C = functools.reduce(lambda x,y: (x[1]+y[1], x[0]+y[0]), pList21A) # adding and concatenating elements in a list
#print(pVal22C)
print(pList21B)
pVal22D = functools.reduce(lambda x,y: (x[1]+y[1], x[0]+y[0]), pList21B) # adding and concatenating elements in a list
print(pVal22D)
the first two reduce functions are going through as expected, but the last two are throwing an error. Output and error is shown below.
Cannot figure out what is going wrong
['Ram', 'RamPM', 'Shyam', 'PMShyam', 'Sita', 'SiPMMta']
[('Ram', 3), ('RamPM', 5), ('Shyam', 5), ('PMShyam', 7), ('Sita', 4), ('SiPMMta', 7)]
[(3, 'Ram'), (5, 'RamPM'), (5, 'Shyam'), (7, 'PMShyam'), (4, 'Sita'), (7, 'SiPMMta')]
----
[('Ram', 3), ('RamPM', 5), ('Shyam', 5), ('PMShyam', 7), ('Sita', 4), ('SiPMMta', 7)]
('RamRamPMShyamPMShyamSitaSiPMMta', 31)
[(3, 'Ram'), (5, 'RamPM'), (5, 'Shyam'), (7, 'PMShyam'), (4, 'Sita'), (7, 'SiPMMta')]
(31, 'RamRamPMShyamPMShyamSitaSiPMMta')
----
[(3, 'Ram'), (5, 'RamPM'), (5, 'Shyam'), (7, 'PMShyam'), (4, 'Sita'), (7, 'SiPMMta')]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-b1b1ac48507f> in <module>()
17 #print(pVal22C)
18 print(pList21B)
---> 19 pVal22D = functools.reduce(lambda x,y: (x[1]+y[1], x[0]+y[0]), pList21B) # adding and concatenating elements in a list
20 print(pVal22D)
<ipython-input-41-b1b1ac48507f> in <lambda>(x, y)
17 #print(pVal22C)
18 print(pList21B)
---> 19 pVal22D = functools.reduce(lambda x,y: (x[1]+y[1], x[0]+y[0]), pList21B) # adding and concatenating elements in a list
20 print(pVal22D)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I am sorry if it is something very simple, but would be grateful if someone could explain why the + operand is being supported in the first two reduce functions but are not supported in the second two reduce functions.
Upvotes: 0
Views: 70
Reputation: 6930
The output of lambda x,y: (x[1]+y[1], x[0]+y[0])
swaps the order of the components.
(3, 'Ram')
and (5, 'RamPM')
→ ('RamRamPM', 8)
.('RamRamPM', 8)
and (5, 'Shyam')
gives error, because it attempts to add 'RamRamPM' + 5
and 8 + 'Shyam'
Upvotes: 1