3

In Python 2, this function definition is valid:

def sv( (L, R) ):
    return L ^ R

However, in Python 3, a syntax error is returned on the second left parenthesis. I can't figure out why?

How do I instruct Python to accept a tuple as input?

2 Answers 2

4

Tuple parameter unpacking was removed in python 3.

https://www.python.org/dev/peps/pep-3113/

Sign up to request clarification or add additional context in comments.

Comments

2

Function parameters are given as single variable names, so you would do:

def sv(l_r):
    l, r = l_r
    return l ^ r

If you want to ensure that this is a tuple, you can use type annotations and mypy

from typing import Tuple
def sv(l_r: Tuple[int, int]) -> int:
    l, r = l_r
    return l ^ r

However this is probably not what you want. Accept two parameters and if you have a tuple to pass in, use the splat operator *.

def sv(l, r):
    return l ^ r

tup = (1, 2)
result = sv(*tup)

Note that this sort of pattern matching isn't generally supported by Python as a language feature, unlike some other languages (Haskell comes to mind). What you want to do in Haskell would be:

sv :: Bits a => (a, a) -> a
sv (l, r) = l `xor` r  -- Note the pattern match here on `(l, r)`

-- contrast with a two-argument function:

sv' :: Bits a => a -> a -> a
sv' l r = l `xor` r

1 Comment

@ColinMac I think that itertools.starmap does that.

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.