Sajid
Sajid

Reputation: 97

How can I create a tuple consisting of class objects?

This question is for Python version 2.7. For example, if I have the following class:

class Example:
    def __init__(self, a, b):
        self.a = a
        self.b = b
object = Example("x", "y")
t = tuple(object)

After executing the code above I get TypeError: iteration over non-sequence because I can only store a single variable of the object inside the tuple and not the object itself. My question is, is there an easy solution to store class objects in tuples such that tuple = (o1, o2, o3) where o1, o2 and o3 are objects?

Upvotes: 2

Views: 6722

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78556

You don't have to call tuple on the object to do this:

obj = Example("x", "y")
t = (obj,) # one item tuple

Be careful to not use the name object to not shadow the builtin object class.

To create a tuple with more than one item:

t = (obj1, obj2, obj3)

Note that the parenthesis serve only for grouping and removing them will not have any effect.

Upvotes: 4

Ami Tavory
Ami Tavory

Reputation: 76297

Your problem doesn't really have to do with the type of the tuple's elements, but rather with single-item tuples. From the documentation:

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

Note the following:

In [1]: a = (1)

In [2]: type(a)
Out[2]: int

In [3]: a = (1, )

In [4]: type(a)
Out[4]: tuple

In [5]: a = 1, 

In [6]: type(a)
Out[6]: tuple

Upvotes: 1

Related Questions