Krist
Krist

Reputation: 31

Appending list issue

So basically what i'm trying to do here is scan a list of words and checking if their corresponding item in a dictionary is in the it_all_paragraphs string.

All the stuff below doesn't really matter, the issue is in the first 6 lines of code, if i do .append(list) then i clear that list basically the master list get cleared too. With a few researches i realized this is happening because is just a pointer not really adding those items in the list.

What i need to do is basically each time the index "i" increases just append all the lists of strings i've found in a list, and for future stuff that are going to be found again a new list in the same list.

Let's say the desired result should be something like:

[["a", "b"], ["c", "d", "e",] , ["f", "g"]]

but instead without the part from line 3 to 7 (that have to be fixed) i get something like:

["a" , "b" , "c" , "d" , "e" , "f" , "g"] which is chaotic for the stuff that i must do later with this. Any suggestion?

for i in range(len(gr_completed_sequences)):

    if len(traduzione_it) == 0:                      #Stuff i'm trying to make work
        pass
    else:        
        ordered_traduzione_it.append(traduzione_it)
        traduzione_it.clear()
                                                     #From here on doesn't really matter
    words = gr_completed_sequences[i].split()
    for c in range(len(words) -1, -1, -1):
        gr_clean_word = words[c].strip(".,:;|?")
        if len(gr_it[gr_clean_word]) == 1:
            traduzione = "".join(gr_it[gr_clean_word])
            if traduzione in it_all_paragraphs:
                traduzione_it.append(traduzione)
                gr_completed_sequences[i] = words
                continue
            else:
                words.pop(c)
                gr_completed_sequences[i] = words

Upvotes: 2

Views: 49

Answers (1)

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9600

That is an expected behavior since both are alias to the same object that can be verified with the following example:

tr = [1, 2]
or_tr = [[3]]
or_tr.append(tr)
print(or_tr)
tr.clear()
print(or_tr)

Output:

[[3], [1, 2]]
[[3], []]

You can avoid that by creating the copy of the list and appending that to the resultant list as follows:

tr = [1, 2]
or_tr = [[3]]
or_tr.append(tr.copy())
print(or_tr)
tr.clear()
print(or_tr)

Output:

[[3], [1, 2]]
[[3], [1, 2]]

Upvotes: 1

Related Questions