why Python can't define tuples in a function?


Since Python 3.0, it is no longer possible to define unpacked tuple as a parameter in a function (PEP 3113). It means if you try to define a function as below −

def fn(a,(b,c)):
   pass


Python interpreter displays syntax error at first bracket of tuple. Instead, define tuple objects as parameter and unpack inside the function. In following code, two tuple objects representing x and y coordinates of two points are passed as parameters to calculate distance between the two. Before calculating, the tuple objects are unpacked in respective x and y coordinates.

def hypot(p1,p2):
   x1,y1=p1
   x2,y2=p2
   import math
   hyp=math.sqrt((x1-x2)**2+(y1-y2)**2)
   return hyp

x=(10,10)
y=(20,20)
print ("hyp=",hypot(x,y))

Updated on: 18-Feb-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements