views:

79

answers:

2

I'm trying to recurse over a list (eg. [True, [[True, False], [False, [False, True]]]]) using Python. I know that the list length will always be 2 and both values will be boolean. I'd like to take those values and substitute them back into the list until there are only 2 values left (or 1 boolean value). Any help would be much appreciated.

+4  A: 

You haven't said how to combine the two parts, so I'm assuming or but you could use another function instead.

l = [True, [[True, False], [False, [False, True]]]]

def foo(x):
    if isinstance(x, list):
        return foo(x[0]) or foo(x[1])
    else:
        return x

print foo(l)
Mark Byers
Perfect, thanks!!
A: 

say your list is l

def print_list(list):
   t = type(list())
   for item in list:
      if type(item) is t:
         print_list(item)
      else:
         print item
 print_list(l)

Something simple like that would print every item in your list.

Jweede
`type(list())` is spelled "`list`".
Mike Graham
true. Spelling it out for the new guy.
Jweede
Well, not exactly spelled list, because in this case Jweede is shadowing the builtin list. So unless the argument passed in happens to be callable, what you're going to get with this is an exception. I'd recommend not using list as the argument to your function ;)
Jeffrey Harris
yeah. The `isinstance` method was a much better choice.
Jweede