Reputation: 700
In python is there a way to initialize a class with n-nested tuples? with x being 0 to n and y being an empty list.
What I mean is:
Suppose you have a class such as:
class NestedTuples:
def __init__(self, tuple):
self.tuple = ?
so if you were to do something like:
t = NestedTuples(4)
it will create:
((0, []), (1, []), (2, []), (3, []))
Upvotes: 0
Views: 96
Reputation: 34047
In [74]: class NestedTuples:
...: def __init__(self, n):
...: self.tuple = tuple((i, []) for i in range(n))
...:
In [75]: t = NestedTuples(4)
In [76]: t.tuple
Out[76]: ((0, []), (1, []), (2, []), (3, []))
Upvotes: 1
Reputation:
This works*:
class NestedTuples:
def __init__(self, num):
self.tuple = tuple((x, []) for x in range(num))
See a demonstration below:
>>> class NestedTuples:
... def __init__(self, num):
... self.tuple = tuple((x, []) for x in range(num))
...
>>> t = NestedTuples(4)
>>> t.tuple
((0, []), (1, []), (2, []), (3, []))
>>>
Lastly, here is a reference on generator expressions.
*Note: I had to rename the tuple
parameter of NestedTuples.__init__
. You should never create a variable that has the same name as one of the built-ins. Doing so will overshadow it.
Upvotes: 2
Reputation: 7929
Simple code:
param = 4
nestedTuple = tuple([(i,[]) for i in range(param)])
print nestedTuple
Output:
((0, []), (1, []), (2, []), (3, []))
Upvotes: 1