Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading