3

What is the most python way to "flip" a list/tuple.

What I mean by flip is: If a you have a tuple of tuples that you can use with syntax like tuple[a][b], "flip" it so that you can do tuple[b][a] to get the same item.

An Example:

t = [
    [1, 2, 3]
    [4, 5, 6]
]

flipped(t) = [
    [1, 4]
    [2, 5]
    [3, 6]
]
2
  • 1
    Note that that is a list of lists, you don't have any tuples. Commented Apr 16, 2017 at 12:32
  • @jonrsharpe whoops. It doesn't really matter, but thanks for pointing that out. Commented Apr 16, 2017 at 19:08

2 Answers 2

8

zip would be it; With zip, you take elements column by column(if you have a matrix) which will flip/transpose it:

list(zip(*t))
# [(1, 4), (2, 5), (3, 6)]
Sign up to request clarification or add additional context in comments.

1 Comment

Better to have a description for your answer.
7

It is called transpose.

>>> t = [
...     [1, 2, 3],
...     [4, 5, 6]
... ]
>>> zip(*t)
[(1, 4), (2, 5), (3, 6)]
>>> map(list, zip(*t))
[[1, 4], [2, 5], [3, 6]]

If t were instead a NumPy array, they have a property T that returns the transpose:

>>> import numpy as np
>>> np.array(t)
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.array(t).T
array([[1, 4],
       [2, 5],
       [3, 6]])

3 Comments

Thanks for letting me know what it's called!
This does not seem to work for tuples ?
It has been tested to work for both lists of tuples and tuples of lists although the zip call will need to be wrapped in a list call for Python 3. That is list(zip(*seq)) as in the other answer.