pwnsauce
pwnsauce

Reputation: 414

What should I use instead of isinstance()

I have to parse some object that is composed of lists. But it can have list within list within list : obj=[[smth1],[[smth2],[smth3]]] each smthX can be a list aswell.

I'm looking for a value that I know is in a "second layer list". In my example, it could be in [[smth2],[smth3]]

What i'm doing right now is iterarating on my object, and testing if what i'm iterating on is a list awell. if it is, I look for my value.

  for list in obj :
    if isinstance(list, obj) :
      for souslist in list :
        I LOOK FOR MY VALUE

But I'm reading everywhere (http://canonical.org/~kragen/isinstance/ a lot of stackoverflow thread) that the use of isinstance() is only for special occasion (and my use doesn't look like a special occasion)

Before using isinstance() I was testing what list[0] returned me in a try/except but it felt even wronger. Any alternate way to achieve this in a clean way ? (I don't have any power over the format of my obj I have to work on it)

Upvotes: 0

Views: 506

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

If you are looking for sub-lists with two item (which are lists) first off you need to check the length (if you are sure that all the items are list) then check if all the items in sub-list are list using isinstance()

for sub in obj:
    if len(sub) == 2 and all(isinstance(i, list) for i in sub): # you can add " and isinstance(sub, list)" if you are not sure about the type of sub 
        look_val(sub)

Upvotes: 1

Related Questions