0

I was trying to solve a problem that contains a code part similar to this. But whenever I tried to execute the script, it turns out to be an infinite loop. What is the reason for this issue and how can I solve it?

a=[1,2]
for i in a:
  a.append(i)
  print("Infinite")

I tried this program locally on my computer and Google Colab, but in both cases. But instead of appending values 1, 2 to list a, it works differently.

I created a copy of a by assigning z=a and changed the structure of for loop like this:

z=a
for i in z:
   a.append(i)

But the issue remains the same:

enter image description here

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

What is happening is every for every iteration of the loop, a new value is added to the list a. This means there is always a new element in the list after every iteration, meaning the loop will never finish.

As for your copy of a, that doesn't exactly create a copy of a. z=a simply references the variable a, and so modifying z also modifies a.

Aaron Boult
  • 246
  • 1
  • 7
0

You shouldn't change the structure of a container while iterating it. Here, you're adding to the end of a while iterating it. That will go on forever.

You were on the right track with your try to fix it. The problem is though, z=a doesn't create a copy of the list; it creates a new reference to the same list.

You need to make a copy explicitly:

z=a[:]  # Copy via slice notation
for i in z:
   a.append(i)

Or just extend a with itself:

a.extend(a)
print(a)  # [1, 2, 1, 2]

Or multiply it:

a *= 2
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117