List storing other lists keeping its old index values after doubling main list size?

Question:

I’m having issues with attempting to double the size of a list that contains lists like so:

main_list = [[], [], [], []]

Say I want to add the word "test" at main_list[1]. That can be done simply by just:

main_list[1].append("test")

However, when I want to double the size of the main_list and therefor double the amount of lists I’m currently doing this:

        for a in main_list:
            while len(a) != 0:
                del a[0]
            if len(a) == 0:
                continue

This is to remove the old main_lists contents because I do not want the old lists contents to carry over to the doubled list.

Followed by:

main_list = main_list * 2

Here is where I run into issues. If I try to append test at index = 0 I would expect the outcome to be:

main_list[0].append("test")
print(main_list) --> [["test], [], [], [], [], [], [], []]

However, the output that I get is instead:

main_list[0].append("test")
print(main_list) --> [["test], [], [], [], ["test], [], [], []]

So the old index values have obviously carried over to the new list. Is there an easy way to fix this? I was thinking about maybe doing a for-loop which forcefully changes the indexes to be correct, but it seems like that would be infeasible after the list has doubled a couple of times.

Asked By: SERO9

||

Answers:

You just need to make a new list of lists for main_list. When you do that, all the old lists will be lost:

size = len(main_list) * 2
main_list = [[] for _ in range(size)]
main_list[0].append("test")
print(main_list)

Output as expected

Answered By: quamrana
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.