Martin
Martin

Reputation: 41

How to print a list using class methods

I have the following class which is designed to print a list where the length of the list varies with the number of arguments entered by the user. It is as follows:

class ListCreator:
    def __init__(self, *i):
        self.list = [i]

    def __str__(self):
        return str(self.list)

When I try to run the following code:

print(ListCreator(4,'Hi',5,6))

The result is this:

[(4, 'Hi', 5, 6)]

How can I change this so the end result is not a tuple consisting of the elements, so it is rather like this:

[4,'Hi',5,6]

I have tried running an if statement to test whether the element is a tuple and then if so, append each element of the tuple into a new list and set self.list to the new list, however I was wondering if there is a nicer way of doing so, especially for the case in which:

print(Circularlist())

should output:

[]

Any help is appreciated, thanks.

Upvotes: 0

Views: 111

Answers (1)

Josh Clark
Josh Clark

Reputation: 1012

When you write [i], you make a list and put i in the first index. i is a tuple. You can convert the tuple directly to a list like this:

self.list = list(i)

Upvotes: 1

Related Questions