1

I have to initialize class with list, which will return every sublists from the given list.

I have a problem with defining empty list as an argument:

class list():
def sublists(self, lst=[]):
    sub = [[]]
    for i in range(len(lst)+1):
        for j in range (i+1, len(lst)):
            sub = lst[i:j]
            sub.append(sub)
    return sub
4
  • 1
    why must this be a class? It has no internal state, as far as I can tell. Also, be careful with a mutable default argument, although in this case it shouldn't be an issue. In any case, what exactly is your issue here? What, exactly is your problem? Note, don't use list as a name for a class, that will shadow the built-in name list Commented Dec 26, 2019 at 0:19
  • @poloOlo what is your goal? Do you need a class instance with an hierarchical list attribute? Or do you need a function to split some hierarchical list into many lists? Commented Dec 26, 2019 at 0:23
  • @juanpa.arrivillaga i have to use 'class' because it's my school exercise. When i'm trying to call my class with arguments (exercise1 = list() exercise1.sublists(1,2,3 OR [1,2,3])) in first case it shows me an error - "sublists() takes from 1 to 2 positional arguments but 4 were given" in 2nd (after i changed 'return' to 'print' in my code) i have this output: [2, [...]] Commented Dec 26, 2019 at 0:51
  • @VictorDDT i need a class instance with an hierarchical list attribute and the class need to be initialize with list Commented Dec 26, 2019 at 0:52

2 Answers 2

2

As others have pointed out, your intention is not quite clear from the question. What I understood is that you want to get all contiguous sublists of a given list.

This achieves that.

class MyList:
    def sublists(self, lst=[]):
        subs = [[]]
        for i in range(len(lst)):
            for j in range (i+1, len(lst)+1):
                sub = lst[i:j]
                subs.append(sub)
        return subs

x = [i for i in range(3)]
my_list = MyList()
print(my_list.sublists(x))

Please update your question if you intend to do something else.

Sign up to request clarification or add additional context in comments.

Comments

2

Correct me if I'm wrong, but I guess the task is quite simple. You can just init your class instance with the list:

class list():
    sub = []
    def __init__(self, lst=[]):
        self.sub = lst

a = [
[1,2,3],
[4,5,6],
[7,8,9],
]

myClass = list(a)

print(myClass.sub)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.