Bizarre behaviour while iterating list
Page 1 of 14 Replies - 487 Views - Last Post: 09 January 2012 - 06:13 AM
Topic Sponsor:
#1
Bizarre behaviour while iterating list
Posted 09 January 2012 - 05:28 AM
Hi, I want to iterate over a list, printing each item and subsequently deleting it, so that at the end, the list is empty, while all the numbers are printed out. I have tried two tactics (to me the logic for both is the same, just checked to spot the problem), but in either case, neither is the list fully empty after the iteration, nor are all the numbers printed. Can somebody tell me what is the problem, and how can I implement what I am trying to do?
Replies To: Bizarre behaviour while iterating list
#2
Re: Bizarre behaviour while iterating list
Posted 09 January 2012 - 05:42 AM
The problem is that you are deleting the elements after printing them, which changes the array by moving each element one index down, while the index is still incremented as if it were dealing with the original array.
I mean, this is basically what is happening:
What you should be doing is either printing each element of the array in a loop, and then clearing the array once all of them have been printed; or printing and deleting always the first index of the array while the array has elements. Something like:
I mean, this is basically what is happening:
# The first iteration a = [1, 2, 3] index = 0 # Prints 1 # The second iteration a = [2, 3] index = 1 # Prints 3 # The third iteration a = [2] index = 2 # Index is outside the range of the array
What you should be doing is either printing each element of the array in a loop, and then clearing the array once all of them have been printed; or printing and deleting always the first index of the array while the array has elements. Something like:
while len(a) > 0:
print a[0]
del a[0]
This post has been edited by Atli: 09 January 2012 - 06:15 AM
Reason for edit:: Fixed the array indexes. (See cupidvogel's next post.)
#3
Re: Bizarre behaviour while iterating list
Posted 09 January 2012 - 05:54 AM
I guess you meant a[0], not a[1], right?, for in Python, just like in C, and unlike, say, Matlab, the starting index is 0 and not 1.
#4
Re: Bizarre behaviour while iterating list
Posted 09 January 2012 - 06:12 AM
O yea, that's right. Sorry. Been reading a lot of LUA code lately.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote





|