2

I am trying to use reduce as follows:

>>> reduce(lambda z,(x,y): (z+1) if x == y else z, [(3, 4), (5, 2), (4, 4), (5, 5)], 0)

In Python 2.7 I get the expected:

2

While the exact same line returns the following error in Python 3.5:

File "<stdin>", line 1
reduce(lambda z,(x,y): (z+1) if x == y else z, [(3, 4), (5, 2), (4, 4), (5, 5)], 0)
                ^

SyntaxError: invalid syntax

Any suggestions as to what the syntax should be for Python 3? Thanks.

gxpr
  • 836
  • 9
  • 12
  • 2
    Yes, this is actually a consequence of the fact that tuple argument unpacking has been removed in python 3. Check [PEP3113](https://www.python.org/dev/peps/pep-3113/). – cs95 Dec 21 '17 at 12:00
  • 1
    Although you can fix the error here, a more elegant way is probably `sum(x == y for x, y in data)` with `data` the list. – Willem Van Onsem Dec 21 '17 at 12:17

1 Answers1

2

tuple pattern matching was removed from python 3, so try:

reduce(lambda z, x: (z+1) if x[0] == x[1] else z, [(3, 4), (5, 2), (4, 4), (5, 5)], 0)

As @cᴏʟᴅsᴘᴇᴇᴅ commented, check PEP3113

Netwave
  • 40,134
  • 6
  • 50
  • 93