Home > Software design >  While appending a list over other list, getting empty list of lists
While appending a list over other list, getting empty list of lists

Time:07-07

code:

def merge_the_tools(string, k):
slist=list(string.strip())
subs=[]
full_subs=[]
for i in range(0,len(string),k):
    for j in range(i,i k):
        subs.append(slist[j])
    print(subs)
    full_subs.append(subs)
    subs.clear()
    print(full_subs)

        

input:
string:AABCAAADA
k:3

output: ['A', 'A', 'B']
[[]] #expected [['A', 'A', 'B']]
['C', 'A', 'A']
[[], []] #expected [['A', 'A', 'B'], ['C', 'A', 'A']]
['A', 'D', 'A']
[[], [], []] #expected [['A', 'A', 'B'],['C', 'A', 'A'],['A', 'D', 'A']]

As you can see in the above code, I'm trying to make a list of lists. But every time the list gets appended to the new list, its forming an empty list of lists. I really can't figure out what's going on here. Please help me out.

CodePudding user response:

Instead of subs.clear(), I used subs=[]. Now the code is working as intended.

CodePudding user response:

def merge_the_tools(string, k):

slist=list(string) # здесь просто из строки делается список
print(slist)
sub=[]
full_sub=[]
for i in range(0, len(string), k):
    sub.clear()
    for j in range(i, i k):
        sub.append(slist[j])
    full_sub.append(sub)
    print(full_sub)

Is it OK?

  • Related