10 Years
Discussion Span
Last Post by vegaseat

if you just want to find "Paul" in your example, one way to do it is to convert that list to string

astring  = ','.join( str(i) for i in nested_list)
if "Paul in astring:
  print "Found"
if "x" in nested

can be written as

for elem in nested: if elem == "x" ...

Your list nested_list = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777, 'Paul']], 13] consists of 5 elemenst:

As you can see, none of these passes the test "Paul" == elem. In the 4th one (]) there is the string Paul, but it is hidden in a list ;)


You can flatten the list, might call this un-nesting and then search ...

def xflatten(seq):
    """a generator to flatten a nested list"""
    for x in seq:
        if type(x) is list:
            for y in xflatten(x):
                yield y
            yield x
nested_list = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777, 'Paul']], 13]
flat_list = list(xflatten(nested_list))
print flat_list  # [1, 'Dick', 2, 'Mary', 7, 9, 700, 777, 'Paul', 13]
if 'Paul' in flat_list:
    print "Found Paul in flat_list"  # now it works!

If you are only searching, Ghostdog's solution is most elegant and can be simplified to ...

nested_list = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777, 'Paul']], 13]
nl_string = str(nested_list)
print nl_string  # "[1, 'Dick', 2, ['Mary', 7, 9, [700, 777, 'Paul']], 13]"
if 'Paul' in nl_string:
    print "Found Paul in the string"  # works too!

Thank you fellow Pythonians. I learned from mawe's explanation that in order to find an item or find the maximum item you have to un-nest the list as shown by vegaseat's code.

Converting the list to a string, as Ghostdog74 suggested, works well for the search, but can't find the maximum.


since you are so refreshingly inquisitive, have you tried this ...

flat_list = [1, 'Dick', 2, 'Mary', 7, 9, 700, 777, 'Paul', 13]
print max(flat_list)

Would you have predicted the outcome? Can you explain why?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.