zip argument #1 must support iteration (did not understand this error)

Asked

Viewed 674 times

2

I have the following code.

  v1 = [1,2]
v2 = [2,1]

def vector_add(v, w):
    '''Soma entre dois vetores'''
    return [v_i + w_i for v_i, w_i in zip(v,w)]

def vector_subtract(v, w):
    '''Subtrai elementos correspondentes'''
    return [v_i - w_i for v_i, w_i in zip(v,w)]

print('Soma -> ', vector_add(v1, v2))
print('Subtração -> ', vector_subtract(v1, v2))

Which is working normally. However, I have one more in which the error appears.

def vector_sum(vectors):
    '''Soma de todos os elementos do vetor'''
    result = vectors[0] #Result recebe o primeiro valor do vetor
    for vector in vectors[1:]: #Depois passa por todos os outros
        result = vector_add(result, vector) #E adiciona ao resultado
    return result

vetorX = [5, 5, 5, 5, 20]
print('Soma de todos os elementos do vetor -> ', vector_sum(vetorX))

This returns me the following error:

--------------------------------------------------------------------------- Typeerror Traceback (Most recent call last) in 7 8 vetorX = [5, 5, 5, 5, 20] ----> 9 print('Sum of all elements of the vector -> ', vector_sum(vetorX))

in vector_sum(Vectors) 3 result = Vectors[0] #Result gets the first vector value 4 for vector in Vectors[1:]: #Then go through all the others ----> 5 result = vector_add(result, vector) #E adds to result 6 Return result 7

in vector_add(v, w) 4 def vector_add(v, w): 5 ''Sum between two vectors'' -----> 6 Return [v_i + w_i for v_i, w_i in zip(v,w)] 7 8 def vector_subtract(v, w):

Typeerror: zip argument #1 must support iteration

Why does this mistake happen?

1 answer

1


According to the documentation, zip takes several iterable objects (such as lists or tuples, for example) as parameters.

In your case, you created vetorX = [5, 5, 5, 5, 20] and passed this list to vector_sum.

Within the function vector_sum, took the first element from the list (result = vectors[0]). At this point, result is equal to 5. In the first iteration of for, you pass this value (5) to vector_add, which in turn passes it to zip.

Only the number 5 is not an eternal object, and that is what is being said in the error message ("zip argument #1 must support iteration").


It is unclear what you want the result to be. If you want to add up all the numbers of vetorX, for example, just do sum(vetorX).

If the goal is to generate a list in which each element is added with the first number of vetorX (except for the first element itself), so it looks like this:

vetorX = [5, 5, 5, 5, 20]
primeiro = vetorX[0]
result = [i + primeiro for i in vetorX[1:]]
print(result) # [10, 10, 10, 25]

Anyway, whatever you’re trying to do, zip is useful to browse two or more lists simultaneously. If you only have one list (in case, vetorX), there’s nothing to use zip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.