0

I am trying to use extend to save data calculated from loop iterations. However, I get the error 'numpy.int64' object is not iterable

x_hat1= commpy.channels.bsc(x[1],0.2)
Distance = []
for i in range(1, 6):
    Distance.extend(hamming_distance(x_hat1,x[i]))

So, I tried adding the loop inside the extend itself as follows

Distance.extend(value for i in range(1, 6), hamming_distance(x_hat1,x[i]))

But I get the error Generator expression must be parenthesized if not sole argument. I checked the parenthesis a couple of times and they are correct. So, I don't know what is wrong.

Briefly, I want to find the hamming distances between one vector and several ones, and save it in the list "Distance" to use it later on.

Thanks

1
  • Does hamming_distance return one item or a list?
    – River
    Commented Jun 9, 2015 at 23:16

1 Answer 1

1

Your problem is extend expects a list as an argument. If you want to use a normal for loop, either make a single element list:

x_hat1= commpy.channels.bsc(x[1],0.2)
Distance = []
for i in range(1, 6):
    Distance.extend([hamming_distance(x_hat1,x[i])])

or use append instead of extend: Distance.append(hamming_distance(x_hat1,x[i])).

If you want to use an implicit for loop, as in your second case, you simply need to restructure your statement.

The reference to i should come before the implicit loop:

Distance.extend(hamming_distance(x_hat1,x[i]) for i in range(1, 6))

Any of these options will work, it's up to you which you would prefer. (Personally the implicit loop is my favorite. It's a one-liner, not to mention much more pythonic than the straight for loop.)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

More info on list.extend vs. the list.append functions in python (as that was your main confusion):

Append:

Appends a single object to the end of a list

Examples:

 >>myList = [1,2,3]
 >>myList.append(4)
 >>myList
 [1,2,3,4]

BUT should not be used to add a whole list of elements

 >>myList = [1,2,3]
 >>myList.append([4,5,6])
 >>myList
 [1,2,3,[4,5,6]]

More info/examples: http://www.tutorialspoint.com/python/list_append.htm

Extend:

Extends a list by using list.append on each element of the passed list

Examples:

 >>myList = [1,2,3]
 >>myList.extend(4)
 >>myList
 [1,2,3,4,5,6]

BUT throws an error if used on a single element

 >>myList = [1,2,3]
 >>myList.extend(4)
 Type Error: 'int' object is not iterable

To extend a single element requires you to make a 1-item list: myList.extend([4])

More info/examples: http://www.tutorialspoint.com/python/list_extend.htm

More on the differences: append vs. extend

Not the answer you're looking for? Browse other questions tagged or ask your own question.