2

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 Answers2

6

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)]
Psidom
  • 209,562
  • 33
  • 339
  • 356
5

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]])
Dan D.
  • 73,243
  • 15
  • 104
  • 123