views:

116

answers:

3

Ok this is my problem. I am trying something like this:

for i in big_list:
   del glist[:]

   for j in range(0:val)
         glist.append(blah[j])

Idea is to reset list and reuse it for next set of data points. The problem is for some reason if the first list had 3 points. Therefore it used

glist[0]
glist[1]
glist[2]

The next list will for some reason continue from index 3 and store last 3 elements in those indexes

glist[0] = 4th elem of new list
glist[1] = 5th elem of new list
glist[2] = 6th elem of new list
glist[3] = 1st elem of new list
glist[4] = 2nd elem of new list
glist[5] = 3rd elem of new list

I am sure it is an issue with allocated space. But how can I achieve this del g_list[:] so the result is

glist[0] = 1st elem of new list
glist[1] = 2nd elem of new list
glist[2] = 3rd elem of new list
glist[3] = 4th elem of new list
glist[4] = 5th elem of new list
glist[5] = 6th elem of new list

Allocating variable from within loop is not an option. Any ideas?

+4  A: 

Change del glist[:] to glist = []. You don't need to "reuse" or "reallocate" in Python, the garbagecollector will take care of that for you.

Also, you use 'i' as the loop variable in both loops. That's going to confuse you sooner or later. :)

Lennart Regebro
i used that to begin with and then replaced it with delbut both did not work
grobartn
I think he was paraphrasing his actual code, but I may be wrong +1 in any case
Vinko Vrsalovic
In fact, I seem to recall reading somewhere that it's actually faster to just destroy and reallocate the list than it is to try reallocating it.
Jason Baker
@grobartn: You need to define "did not work". Or provide an example. It's best to either update your question or create a new question with your revised code.
S.Lott
That said, I don't actually get your error. Are you not in fact looping over glist as well? That would give this sorts of effects, I think.
Lennart Regebro
I could not paste the actual code because it is copyrighted...this was just summary of the problem and had typo
grobartn
+1  A: 

you can try

glist=[]
ghostdog74
+1  A: 

del glist[:] works fine for clearing a list. You need to show us your exact code. As shown below, the behavior you're describing does not happen. The append after the del a[:] puts the item at index 0.

>>> a = [1,2,3]
>>> del a[:]
>>> a
[]
>>> a.append(4)
>>> a
[4]
FogleBird