0
votes

I am attempting to loop through a matrix, called lattice, randomly using the randrange function. My matrix is an 8x8 and prints fine. However when I attempt to randomly loop through each element of this matrix I am getting the error

'TypeError: 'int' object is not iterable'

Due the upper limit of the range, len(mymatrix). I'm unsure as to why this is.

   for R1 in randrange(0, (len(lattice)):
        for R2 in randrange(0, len(lattice)):
            H = -j*lattice[R1,R2]*(lattice[R1+1,R2],lattice[R1-1,R2], lattice[R1,R2+1],lattice[R1,R2-1]) +h*lattice[R1,R2]
            H_flip = -j*-1*mymatrix[R1,R2]*(lattice[R1+1,R2],lattice[R1-1,R2], lattice[R1,R2+1],lattice[R1,R2-1]) +h*lattice[R1,R2]
    print lattice[R1,R2]

I have not used randrange in a loop before, is it perhaps that it can't be used the same way range is used? I've also tried to set the range as:

for R1 in randrange(0, len(lattice)-1)

I thought maybe the length was one too long but to no avail.

2
Please post the some more details of your code as well as the the full error.Vasilis G.
Just read the docs what random.randrange returns and compare it to what range returns.Michael Butscher
Why are you trying to loop randomly?Olivier Melançon

2 Answers

0
votes

You are correct. randrange() returns a single element from within the given range. On the other hand, range() returns a list of elements, and is therefore iterable.

You could try something like this:

stop = randrange(0, len(lattice)-1)
start = randrange(0, stop)
for R1 in randrange(start, stop):
     for...
0
votes

The method randrange does not return a range, but a randomly selected element instead as can be read in the doc.

random.randrange(start, stop[, step])

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

That is why you get a TypeError, you are indeed trying to loop over an int.

I would not recommend looping in a random order over your lists, but if it turns out to be necessary, I would use shuffle.

from random import shuffle

# shuffle mutates your list so we need to do the following
rows, cols = range(len(lattice)), range(len(lattice))
shuffle(rows)
shuffle(cols)

for R1 in rows:
        for R2 in cols:
            # ...

Note that in Python3, you would need to cast your range to a list first.