0

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)

4
  • 2
    Your use of isinstance seems fine to me, actually. 99% of my own isinstance use is when I'm iterating through a collection of heterogeneous types, which appears to be exactly what you're doing here. (I'm posting this as a comment and not an answer because it's only my opinion.) Commented May 18, 2016 at 14:45
  • What you mean exactly by second layer list? if you want to find the items that are 2 nested lists you cannot achieve this in first loop. Commented May 18, 2016 at 14:45
  • There is nothing wrong with using isinstance in your case. Your first approach was also ok, as Python believes in "easier to ask for forgiveness than permission": docs.python.org/3.4/glossary.html#term-eafp Commented May 18, 2016 at 14:49
  • @Kasramvd I know my value will be obj[x][y] it cannot be neither obj[x] or obj[x][y][z], in fact it will be obj[x][1] Commented May 18, 2016 at 14:50

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.