poloOlo
poloOlo

Reputation: 43

Python initialize class with list

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

Upvotes: 1

Views: 2352

Answers (2)

VictorDDT
VictorDDT

Reputation: 613

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)

Upvotes: 2

Stuxen
Stuxen

Reputation: 738

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.

Upvotes: 2

Related Questions