-2

I'm using anaconda Python 3 notebook. And When I Try to append anything to a list, my pc goes mad. It gets slow, the RAM goes to 95% and it just wont work anymore. But i noticed somethin, the problem only occurs when I use a for statement. and if I use slice brackets I dont have that problem, so thi would be like this:

Problem:

for element in anylist:
       anylist.append('whatever')

(So far, i think this one never stop working and it may be causing some truobles. I dont really know)

No problem:

for element in anylist[:]:
      anylist.append('whatever')

Another detail: All this started right before I imported the String module, and the Os module. But now it happens every time i write single code.

Python is in 64 bits as it has to be in my case. If you could help me I would appreciate it.

depperm
  • 10,606
  • 4
  • 43
  • 67
  • 1
    the first example runs forever because you are constantly adding to the list you're looping through, the second example loops through a copy of `anylist` – depperm Jun 23 '17 at 17:29

2 Answers2

3

The first example can be translated as:

while there is something more in anylist add whatever to the end

which means the list will grow until the system crashes.

So it will never end. The second translates as:

for the number of items in anylist add whatever to the end of the list.

So will double the length of the list.

Hence python is doing exactly what you are telling it to do, (which I suspect is not what you think you are doing).

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
  • Thanks for the help. I know it was a silly mistake, i guess thats why my question got a -2. I´m new here so I´m sorry if this was an already answered question or something. – Sebastián Meléndez Jun 23 '17 at 19:46
0

Try doing:

for element in range(len(anylist)):
    anylist.append('something')
GiodoAldeima
  • 153
  • 7