In my recently migrated from 2 to 3 Python code I have
list(reversed(zip(*positions)))
which generates the error
TypeError: 'zip' object is not reversible
I can fix this by changing the problematic code to
list(reversed(list(zip(*positions))))
but this seems like the wrong way to go about it.
What is the correct way to revers a zip
in Python 3?
reversed
is used to iterate on the list. It doesn't create a list on purpose, because it's often used just to iterate backwards on elements, not to create lists.
That's why you have to use list
on it to create a list
. And it needs a sequence to be able to get to the last element directly so you have to do list(zip())
in python 3.
Maybe you could shorten
list(reversed(list(zip(*positions))))
to
list(zip(*positions))[::-1]
it creates a list
directly without the need for reverse
so it's probably slightly faster too.