Flatten... or How to determine sequenceability?

Chad Everett chat at linuxsupreme.homeip.net
Fri May 25 12:24:27 EDT 2001


On Fri, 25 May 2001 15:52:28 GMT, Leighton Pritchard <lep at aber.ac.uk> wrote:
>On Fri, 25 May 2001 10:44:57 -0400, Noel Rappin <noelrap at yahoo.com>
>made a brave stab at grammar with:
>
>>I'm writing code that needs to flatten a multi-dimension list or tuple into 
>>a single dimension list.
>>
>>[1, [2, 3], 4] => [1, 2, 3, 4]
>>
>>As part of the algorithm, I need to determine whether each object in the 
>>list is itself a sequence or whether it is an atom.  Using the types module 
>>would cause me to miss any sequence-like object that isn't actually the 
>>basic type.  So, what's the best (easiest, most foolproof) way to determine 
>>whether a Python object is a sequence?
>>
>>Thanks,
>>
>>Noel Rappin
>
>Funny you should ask this, as there's been a similar thread on the
>Python-Tutor list, in which the following link:
>
>http://aspn.activestate.com/ASPN/Mail/msg/python-Tutor:454781
>
>was mentioned. It contains an excellent flatten() function that might
>do just what you're looking for.
>

and here it is:

def flatten(L):
	if type(L) != type([]): return [L]
	if L == []: return L
	return flatten(L[0]) + flatten(L[1:])




-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----



More information about the Python-list mailing list