Search code examples
pythonpython-3.xpython-2.7python-zip

zip giving error in updating code from python 2.7 to python 3.6


I am trying to update some code written in python 2.7 for use in python 3.9. A line using the 'zip' function keeps throwing an error.

mask_1 = np.asarray([w1 & w2 for w1,w2 in zip(mask_1[::2],mask_1[1::2])])

The error reads:

TypeError: unsupported operand type(s) for &: 'str' and 'str'

My understanding is that I should cast 'zip' into the form of list for python 3.9 i.e.:

mask_1 = np.asarray([w1 & w2 for w1,w2 in list(zip(mask_1[::2],mask_1[1::2]))])

Then the error becomes

TypeError: unsupported operand type(s) for &: 'str' and 'str'

It would appear that '&' is an acceptable operand for 'str' types in python 2.7 but not python 3.6. What is a suitable workaround?


Solution

  • No, the thing that for operates doesn't have to be a list, so that's why changing that changes anything.

    The problem is exactly as stated in the error: you're trying to use the binary operator & on strings (type str), and that makes no sense. So, that's a bug somewhere else!

    Probably, you have some logic somewhere that assumes that strings are essentially bytes; that's not true under Python3. So, find the code that creates mask_1 and make sure it actually creates something that contains integers that can be combined using & – either something like an actual bytes object, or any container of integers; be it just a list of ints, or a numpy ndarray of uint8, or something else.