1

I am trying to make a program that finds a certain value in a nested list, so I wrote this code:

list = [['S', 'T', 'U', 'T'], ['O', 'P', 'Q', 'R']]

However, when I inputted

list.index('O')

It gave me an error message saying

Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list.index('O')
ValueError: 'O' is not in list

Any ideas?

1
  • Very clearly worded. I'm curious the best way to do this too. Commented Apr 3, 2016 at 3:11

2 Answers 2

2

Well it is really simple, 'O' is not in the list, it only contains the other lists. Here is an example:

list_you_have = [['S', 'T', 'U', 'T'], ['O', 'P', 'Q', 'R']]
print list_you_have.index(['O','P','Q','R']) #outputs 1

Now if you do it like:

print list_you_have[1].index('O') # it outputs 0 because you're pointing to 
#list which acctualy contains that 'O' char.

Now a function for nested char search would be

def nested_find(list_to_search,char):
    for i, o in enumerate(list_to_search):
        if char in o:
            print "Char %s found at list %s at index %s" % (char, i, o.index(char))

Or maybe an even simpler solution as @zondo commented would be:

def nested_find(list_to_search,char):
    newlist = sum(list_to_search, [])
    if char in newlist:
        print "Char %s is at position %s" % (char, newlist.index(char))
Sign up to request clarification or add additional context in comments.

Comments

0

You can solve your problem in one-line:

print item in reduce(lambda x, y: x + y, nestedlists)

1 Comment

You can use sum(nestedlists, []) instead of that long reduce() call.

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.