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

How to increment an integer in a list iteratively within a while loop

Can anyone help me with understanding this please? I’m using a while loop to increment an integer within a list and then i’m trying to add the list to another list to create a list of lists. The list of lists has the expected number of elements but they all show the incremented integer as it would be at the end of the while loop not at each iteration of the while loop.

Here’s what I’ve tried:

my_start_list = [1, 2, 3, 4]
my_end_list = []

while my_start_list[0] != 6:
    my_start_list[0] += 1
    my_end_list.append(my_start_list)

print(my_start_list)
print(my_end_list)

and here’s what i get:

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

[6, 2, 3, 4]
[[6, 2, 3, 4], [6, 2, 3, 4], [6, 2, 3, 4], [6, 2, 3, 4], [6, 2, 3, 4]]

And I was kind of expecting:

[6, 2, 3, 4]
[[2, 2, 3, 4], [3, 2, 3, 4], [4, 2, 3, 4], [5, 2, 3, 4], [6, 2, 3, 4]]

Can anyone explain what is going on here or point me in a direction that could explain this?

>Solution :

Here the list you are appending is working as a pointer rather than an separate entity. so you need to hard copy the list at each iteration.

my_start_list = [1, 2, 3, 4]
my_end_list = []
c = []

while my_start_list[0] != 6:
    my_start_list[0] = my_start_list[0] + 1
    c = my_start_list.copy()
    my_end_list.append(c)

print(my_start_list)
print(my_end_list)

Output:

[6, 2, 3, 4]
[[2, 2, 3, 4], [3, 2, 3, 4], [4, 2, 3, 4], [5, 2, 3, 4], [6, 2, 3, 4]]
​
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