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

Question:

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:

[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?

Asked By: ste_b

||

Answers:

You must create a copy the list you are going to append, otherwise you are always appending the same list:

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.copy()) # appends a copy of the list

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]]
Answered By: Joan Lara

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]]
​
Answered By: saicharan sridhara

Would i be right in saying that the while loop is evaluating the…

my_start_list[0] += 1

…first and then appending that final value 5 times to my_end_list?

Answered By: ste_b
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.