[Tutor] Re: flattening and clumping lists

kevin parks cpsoct@lycos.com
Sun, 31 Dec 2000 22:28:47 +0900


I would love to know how to flatten a list. For example if i write the following code to make a palendrome

# mirror.py -- [1,2,3] returns [1,2,3,2,1]
# how to make it return [1,2,3,2,1,2,3,2,1]
# this should really be a tuple so that it is preserved.

l=[1, 2, 3, 4, 5, 6, 7]
foo=l[:-1]      #copy list, excluding last element
foo.reverse()   #flip it
l.append(foo)   #stick it on the end of the other list
#we need to flatten it some how in to a single list
print l

------- snip ------
but i get in return a list with the appended list tacked on as a single element like: [1, 2, 3, 4, 5, 6, 7, [6, 5, 4, 3, 2, 1]]

I thought that there was a thing where you could say flatten(l), but i'll be damned if i can find it now. 

additionally i would like to make a single list into a list of sublists with a random number of elements with a list like this:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

i might get: [[1], [2], [3, 4, 5], [6, 7], [8,9,10]]

but i would need to know how to flatten and clump lists first to be able to do this.

I am trying to make some list processing funcs (or eventually classes). I also wonder if such funcs already exists. I found a few that were on the "Vaults" page, but not as much as i'd thought of the flavors i was a seeking. I have many in mind, but am trying to just take a few baby steps to start with.

cheers & happy new year,
kevin parks,
seoul, korea




Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com