pythonarraysfunctiontuples

Can these two Python functions be replaced by a single generic one taking either a list or a tuple argument?


Can these two Python functions:

def negativeList(a):
  return [-e for e in a]

def negativeTuple(a):
  return tuple(-e for e in a)

be replaced by an equvalent single generic function negative(a)?


Solution

  • You can determine the type at run time

    def negative(a):
        return type(a)(-e for e in a)