Andrew
Andrew

Reputation: 146

First element in list/nested lists

I have a list, which can either be list[] or list[][], and I want to get the very first actual element, which is either list[0] or list[0][0]. What would be the most pythonic way to do this?

Upvotes: 0

Views: 523

Answers (5)

Leo Arad
Leo Arad

Reputation: 4472

You can try

ls[0][0] if isinstance(ls[0], list) else ls[0]

This will return the ls[0][0] if ls containing a list in the first value else the first value of the ls.

Upvotes: 2

Meccano
Meccano

Reputation: 537

The suggested methods will work in your case, but let me suggest a more generic method:

elem = mylist
while type(elem) == list:
    elem = elem[0]

At the end of this loop,elem will contain the first element.

It will achieve the objective for even higher dimensional lists, or even non-list objects (it will just not run the loop at all).

Upvotes: 1

Prathamesh
Prathamesh

Reputation: 1057

Something like this,

l1=[1]

try:
    a=l1[0][0]
    print("two diamensional")
except:
    print("one diamensional")

hope this helps you!

Upvotes: 0

Red
Red

Reputation: 27547

You can do this:

try:
    print(l[0][0])
except:
    print(l[0])

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

Straightforward approach is most Pythonic here:

elem = mylist[0]
if isinstance(elem, list):
    elem = elem[0]

If a dimension might be length zero, this will raise an IndexError, but that's probably what you want anyway.

Upvotes: 0

Related Questions