Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python can't define tuples in a function [duplicate]

For some reason in python everytime I try to define tuples in a function I get a syntax error. For example I have a function that adds vectors to the program, it looks like this:

def add_vectors((angle_1, l_1),(angle_2, l_2)):
    x=math.sin(angle1)*l_1+math.sin(angle2)*l_2
    y=math.cos(angle1)*l_1+math.cos(angle2)*l_2

    angle=0.5*math.pi-math.atan2(y, x)
    length=math.hypot(x, y)
    return (angle, length)

Which seems alright, but the interpretor says there is a syntax error and highlights the first bracket of the first tuple. I am using Python 3.2.3. What am I doing wrong?

like image 436
user3002473 Avatar asked Nov 17 '13 20:11

user3002473


People also ask

Does Python tuple allow duplicates?

31.2 Python Collection Types Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.

Can you make a copy of a tuple?

Copy a tuple. You cannot copy a list with the = sign because lists are mutables. The = sign creates a reference not a copy. Tuples are immutable therefore a = sign does not create a reference but a copy as expected.

Can we add repeated values to the tuples?

Using the '*' operator.The repetition operator duplicates a tuple and links all of them together. Even though tuples are immutable, this can be extended to them.

Can you add 2 tuples in Python?

You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples. You can only add or combine same data types. Thus combining a tuple and a list gives you an error.


2 Answers

Tuple parameters are no longer supported in Python3: http://www.python.org/dev/peps/pep-3113/

You may unpack your tuple at the beginning of your function:

def add_vectors(v1, v2):
    angle_1, l_1 = v1
    angle_2, l_2 = v2
    x=math.sin(angle1)*l_1+math.sin(angle2)*l_2
    y=math.cos(angle1)*l_1+math.cos(angle2)*l_2

    angle=0.5*math.pi-math.atan2(y, x)
    length=math.hypot(x, y)
    return (angle, length)
like image 158
Maxime Lorant Avatar answered Oct 06 '22 15:10

Maxime Lorant


There is no syntax for such tuple unpacking. Instead, take two tuples as arguments on their own and then unpack them into separate arguments.

def add_vectors(tup1, tup2):
    angle_1, l_1 = tup1
    angle_2, l_2 = tup2
    ...
like image 31
justinas Avatar answered Oct 06 '22 15:10

justinas