-1

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?

ste_b
  • 3
  • 2
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Ignatius Reilly Feb 11 '23 at 16:32
  • [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment) – Ignatius Reilly Feb 11 '23 at 16:32

2 Answers2

0

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]]
Joan Lara
  • 1,362
  • 8
  • 15
0

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]]
​