Flatten a list/tuple and Call a function with tuples
Neil Cerutti
horpner at yahoo.com
Wed Jul 25 14:49:10 EDT 2007
On 2007-07-25, Neil Cerutti <horpner at yahoo.com> wrote:
> On 2007-07-25, Jeff <jeffober at gmail.com> wrote:
>> Here's a quick flatten() function:
>>
>> def flatten(obj):
>> if type(obj) not in (list, tuple, str):
>> raise TypeError("String, list, or tuple expected in
>> flatten().")
>> if len(obj) == 1:
>> if type(obj[0]) in (tuple, list):
>> return flatten(obj[0])
>> else:
>> return [obj[0]]
>> else:
>> return [obj[0]] + flatten(obj[1:])
>>
>> x = [1, 2, (3, 4)]
>> y = (1, 2, [3, 4])
>> z = "It even works with strings!"
>> d = {"foo": "bar", "baz": "bat"}
>
> e = [[1], 2, 3, , 4]
Please excuse my bad typography. The above should've been
e = [[1], 2, 3, 4].
--
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
More information about the Python-list
mailing list