Home > Net >  Tuple not list in Jupyter
Tuple not list in Jupyter

Time:01-07

I am writing a class for quaternions. I would like to give the quaternion coordinates as a tuple, not as a list. How can I do this?

Here is my code:

class Quaternion(object):

    def __init__(self, elements):
        if len(elements) != 4:
            raise ValueError("Quaternion init vector must be of length 4.")
        self.elements = elements

What to do to write elements as a tuple not as list. When I try to run my program in Jupyter everything is good, but I must type Quaternion([1,2,3,4]) - so it is not a tuple, but list.

CodePudding user response:

If you can't change the way you call it to:

Quaternion((1,2,3,4))

use the tuple() function to convert the list to a tuple:

class Quaternion(object):

    def __init__(self, elements):
        if len(elements) != 4:
            raise ValueError("Quaternion init vector must be of length 4.")
        self.elements = tuple(elements)

CodePudding user response:

You can define a tuple using any sequence, including lists, in the body of the function.

def __init__(self, elements: Sequence):
    if len(elements) != 4:
        raise ValueError("...")
    self.elements = tuple(elements)

However, since a quaternion must have 4 components, be explicit about that in __init__, and let a class method produce an instance from an "arbitrary" sequence.

def __init__(self, a, b c, d):
    self.elements = (a, b, c, d)

@classmethod
def from_sequence(cls, elements: Sequence):
    try:
        a, b, c, d = elements
    except ValueError:
        raise ValueError("Quaternion init vector must be of length 4.")
    return cls(a, b, c, d)
  • Related