Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 --> 3: object of type 'zip' has no len()

I'm following a tutorial on neural nets1

It's in Python 2.7. I'm using 3.4. This is the line that troubles me:

if test_data: n_test = len(test_data)

I get: TypeError: object of type 'zip' has no len().

Is there a way to rewrite it so that it works in 3.4?

like image 846
Ada Stra Avatar asked Jun 23 '15 19:06

Ada Stra


People also ask

How do you find the length of a zip object?

If it refers to zip objects, then there is no way to count the length. zip has no len() . We can re-cast it to a list, which does have a len(). Once we convert it to a list, the zip object will be consumed.

Does Python have no Len?

The Python "TypeError: object of type 'function' has no len()" occurs when we pass a function without calling it to the len() function. To solve the error, make sure to call the function and pass the result to the len() function.

What is a python zip object?

Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

Can zip take three lists Python?

Python zip three listsPython zipping of three lists by using the zip() function with as many inputs iterables required. The length of the resulting tuples will always equal the number of iterables you pass as arguments. This is how we can zip three lists in Python.


2 Answers

A bit late now to answer, but in case anyone else stumbles on it: for that same neural net example tutorial, it turned out I had to wrap the 3 zip calls in the mnist_loader with a list(zip(...)) construct:

training_data = list(zip(training_inputs, training_results)) (...) validation_data = list(zip(validation_inputs, va_d[1])) (...) test_data = list(zip(test_inputs, te_d[1])) 

And then it worked.

like image 129
Nicolas Turgeon Avatar answered Oct 04 '22 00:10

Nicolas Turgeon


If you know that the iterator is finite:

#NOTE: `sum()` consumes the iterator n_test = sum(1 for _ in test_data) # find len(iterator) 

Or if you know that test_data is always small and a profiler says that the code is the bottleneck in your application then here's code that might be more efficient for small n_test:

test_data = list(test_data) n_test = len(test_data) 

Unfortunately, operator.length_hint() (Python 3.4+) returns zero for a zip() object. See PEP 0424 -- A method for exposing a length hint.

like image 23
jfs Avatar answered Oct 04 '22 00:10

jfs