user7579444
user7579444

Reputation:

How to get elements out from list of lists when having the same position

I have a list of lists where I want to extract the element from each list at same position. How do I do so? As an example. I have like:

L = [[A,B,C,D][B,C,D,E][C,D,E,F]]

Now I want all the letters from position 0 which would give me:

A, B, C - > L[0][0], L[1][0], L[2][0]

I tried to use:

[row[0] for row in L] 

and

L[:-1][0]

But none of them works for me.

Upvotes: 0

Views: 1165

Answers (4)

timgeb
timgeb

Reputation: 78690

Transpose your list with zip.

>>> L = [['A','B','C','D'],['B','C','D','E'],['C','D','E','F']]
>>> t = zip(*L) # list(*zip(L)) in Python 3

t[position] will give you all the elements for a specific position.

>>> t[0]
('A', 'B', 'C')
>>> t[1]
('B', 'C', 'D')
>>> t[2]
('C', 'D', 'E')
>>> t[3]
('D', 'E', 'F')

By the way, your attempted solution should have worked.

>>> [row[0] for row in L] 
['A', 'B', 'C']

If you only care about one specific index, this is perfectly fine. If you want the information for all indices, transposing the whole list of lists with zip is the way to go.

Upvotes: 0

esp
esp

Reputation: 39

The reason this is happening to you is because of the way you made your list.

[[A,B,C,D][B,C,D,E][C,D,E,F]]

You have to separate the list (i.e you forgot the commas in between each list). Change your list to something like this

[[A,B,C,D],[B,C,D,E],[C,D,E,F]]

Also, when testing this it doesn't work as its not in quotation marks, but i'm guessing there's a reason for that.

Hope I could help :3

Upvotes: 2

Afik Friedberg
Afik Friedberg

Reputation: 340

This should work, I don't understand why its not work for you:

[row[0] for row in L] 

output:

['A','B', 'C']

Upvotes: 0

Kyle Swanson
Kyle Swanson

Reputation: 1428

You are very close. Try this,

[v[0] for i, v in enumerate(L)]

Upvotes: 0

Related Questions