Skip to content Skip to sidebar Skip to footer

Pythonic Way To Flip A List/tuple

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 ca

Solution 1:

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)]

Solution 2:

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]])

Post a Comment for "Pythonic Way To Flip A List/tuple"