Search code examples
pythonlistmatrixtransposeindices

How to slice the nth column of a list of lists?


I want to slice the the nth column of a list of lists. e.g.

matrix = [
    ["c","b","a","c"],
    ["d","a","f","d"],
    ["g","h","i","a"]
]

Do i need to transpose the list and then use indices? e.g.

transposed = []
for i in range(len(matrix)+1):
   transposed.append([row[i] for row in matrix])
transposed[1]
>>> ['b','a','h']

or is there a way to use indices directly on the nested list?

I was trying something like:

matrix[:][1]
>>>['d','a','f','d']

but this does not work as I found out.

Thank you


Solution

  • >>> [column[1] for column in matrix]
    ['b', 'a', 'h']
    

    Is this what you meant?