Home > Mobile >  Simple 1D Array Iteration Error (TypeError: 'int' object is not iterable)
Simple 1D Array Iteration Error (TypeError: 'int' object is not iterable)

Time:02-15

I'm currently trying to iterate arrays for Random Walks, and I am able to use a for loop when there are multiple numbers per element of the array. I seem to be having trouble applying a math.dist function to a 1-dimensional array with one number per element.

Here is the problematic code:

origin = 0

all_walks1 = []
W = 100
N = 10
list_points = []
for i in range(W):
    x = 2*np.random.randint(0,2,size=N)-1
    xs = cumsum(x)
    all_walks1.append(xs)
    list_points.append(xs[-1])
    
list_dist = []

for i in list_points:
    d = math.dist(origin, i)
    list_dist.append(d)

If I try to append the distances to a new array, I am getting a TypeError: 'int' object is not iterable error.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1808/1512057642.py in <module>
     16 
     17 for i in list_points:
---> 18     d = math.dist(origin, i)
     19     list_dist.append(d)
     20 

TypeError: 'int' object is not iterable

However, if the array I am parsing through in the for loop is has multiple numbers per element, as it is in the following code, everything works fine:

origin = (0, 0, 0)

all_walks_x = []
all_walks_y = []
all_walks_z = []

W = 100
N = 10

list_points = []

for i in range(W):
    x = 2*np.random.randint(0,2,size=N)-1
    y = 2*np.random.randint(0,2,size=N)-1
    z = 2*np.random.randint(0,2,size=N)-1
    xs = cumsum(x)
    ys = cumsum(y)
    zs = cumsum(z)
    all_walks_x.append(xs)
    all_walks_y.append(ys)
    all_walks_z.append(zs)

    list_points.append((xs[-1], ys[-1], zs[-1]))


list_dist = []

for i in list_points:
    d = math.dist(origin, i)
    list_dist.append(d)

I have tried using for i in range(len(list_points): and for key, value in enumerate(list_points): to no success. The only difference between the first and and the second list_points arrays would appear to be the elements enclosed in parentheses when there are multiple numbers per element. It would seem to be a simple solution that in whatever way is eluding me. Thanks for reading, and any help would be appreciated.

EDIT: I may be using the terms 1D and 3D arrays incorrectly, The first array is a list of numbers such as [6, 4, -1, 5 ... ] and the second array is a list of multiple numbers per element such as [(-10, -2, 14), (12, 2, 8), (-4, 8, 24), (10, 10, 0), (2, 8, 10) ... ]

CodePudding user response:

It seems you are passing integers to math.dist. math.dist finds the Euclidean distance between one and two dimensional points. Therefore you have to provide a list, even if its just a single integer.

Example:

# not valid
math.dist(1, 2)

# valid
math.dist([1], [2])
  • Related