Praveen
Praveen

Reputation: 74

Python zip function performs abnormally, Cannot append to list properly

I have the below code. When it run separately I will get the final_list as

[[1, 10, 20], [2, 11, 21], [3, 10, 22], [1, 10, 23]]

But if I run within another loop I am getting as

[[1, 10, 20, 23], [2, 11, 21], [3, 10, 22], [1, 10, 20, 23]]
   final_list= [[1, 10], [2, 11], [3, 10], [1, 10]]
   list_present= [20, 21, 22, 23]
   for val, val2 in zip(final_list, list_present):
       val.append(val2)

Here is the full program:

x = [[1, 2, 3], [10, 11],[20, 21, 22, 23]]
y = ['a', 'b', 'c']
final = []
list_present = []
list_previous = []
for row in x:
    final_list = []
    len_final = len(final)
    if len_final == 0:
        for attr_val in row:
            final.append([attr_val])
    else:
        list_present = row
        len_array = len(list_previous) - len(list_present)
        if len_array > 0:
            list_present.extend(list_present[:abs(len_array)])
            final_list = list_present
            for val1, val2 in zip(final, final_list):
                val1.append(val2)
        else:
            list_previous.extend(list_previous[:abs(len_array)])
            final_list = list_previous
            for val1, val2 in zip(final_list, list_present):
                val1.append(val2)
    list_previous = final

Upvotes: 0

Views: 39

Answers (1)

Heike
Heike

Reputation: 24420

It's not a problem with zip, it's a problem with this line:

list_previous.extend(list_previous[:abs(len_array)])

You are extending list_previous with the exact same objects that appear at the beginning of the list. This is fine for immutable object like int, but in this case the elements in list_previous are lists. This means that when you append elements to the first sub-lists in the following for-loop, you are also appending them to the last sub-lists since these refer to the exact same objects. To avoid this you could do something like

list_previous.extend(lst[:] for lst in list_previous[:abs(len_array)])

which will extend list_previous with copies of the first few sub-lists rather than the sub-lists themselves.

Upvotes: 1

Related Questions