user856358
user856358

Reputation: 593

How to reinitialize list in loop iteration?

I'm trying to create draws without replacement, and output the result of each draw as a text file. The list is in a separate file, and I want to re-import it for each iteration of my loop

import random
import numberlist

counter=0
draws= 100
while (counter<draws):
    x=  numberlist.listX     #this imports a list of strings eg. ['a341','c32k','42b]]

    random.shuffle(x)     

    x.pop()
    """OPERATIONS WITH POPPED VALUE"""

    counter += 1

What I was hoping for was that X would be realitialized to the the complete listX at the beginning of every loop iteration. Instead what I"m finding is that every time I pop a number, the list gets smaller every loop iteration. Why is this happening, and how can I get around it?

Thank you.

Upvotes: 0

Views: 1136

Answers (2)

johnecon
johnecon

Reputation: 343

As shown here when pop is called in a list it removes the item at the given position in the list, and return it.

Considering you are creating a new reference to the same object using

x= numberlist.listX 

as said above, it is expected that the list will not have the same elements in each loop iteration.

My suggestion is to do something like:

import random

counter=0
draws= 100
xlist = ['a341','c32k','42b']
while (counter<draws):
    x = xlist

    random.shuffle(x)     

    print x[-1]
    """OPERATIONS WITH POPPED VALUE"""

    counter += 1

where

x[-1]

just returns the last element of the list.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250981

You must use a shallow copy of the list:

x=  numberlist.listX[:]  #or list(numberlist.listX)

Using just x= numberlist.listX only creates a new reference to the same object.

Example:

In [1]: lis=[1,2,3]

In [2]: x=lis

In [3]: x is lis  #both point to the same object
Out[3]: True

In [4]: x=lis[:]  #create a shallow copy

In [5]: x is lis 
Out[5]: False

I think you can replace your while loop with this:

for item in (random.choice(lis) for _ in xrange(draws)):
    #do something with item

Upvotes: 4

Related Questions