Toomatoo Toomatoo - 1 year ago 57
Python Question

How to get the first element of a complex list in Python

In Python, I used to get first element of a 2-d list by

a = [[0, 1], [2, 3]]
# [0, 2]

Now, the list is sort of complex, the way to get the first elements does not work

a = [['sad', 1], ['dsads', 2]]
# ['sad', 1]

I do not know what is the difference here. And how to get the first elements in this simple way, rather than

[e[0] for e in a]

Answer Source

you could use in-built zip :

aggregates elements from each of the iterables

a = [['sad', 1], ['dsads', 2]]

#results :
('sad', 'dsads')

You can convert the final result to list from tuple if necessary. * is used to flatten the list into its elements - zip accepts iterables as positional arguments. zip is sort of matrix transposition.

As commented, your first solution (a[:][0]) is not correct, it simply takes the first element of the list. Here you need to first transform the list such that each first elements are grouped into separate list, and so on for second, third .. elements. Then take the first element.


From @Rawing's comment: If the list is very large, consider using


This is the iterator version - this takes the list element only as necessary. In this case, it constructs each elment of the result one at a time, since we need the first element, we use next a single time to get the next (thus, first here) element of the iterator.