[Tutor] flatten

C Smith smichr at hotmail.com
Thu Apr 7 14:00:38 CEST 2005


After posting the suggestion about splitting a string that contained a  
quoted string, I looked back at my (at least I think it’s mine) flatten  
routine and didn’t see anything like it at ASPN. Before I would post it  
there, does anyone see any problems with this non-recursive approach?

I know that there are iterator approaches, but since the list already  
exists is there any problem with flattening the whole thing? Or is part  
of the problem that there may be iterable things that don’t need to be  
completely “iterated to completion” before being able to yield the next  
element? (Does that make sense?)

After searching for "Tim Peters flatten" I was able to find a similar  
routine at

http://sourceforge.net/project/ 
showfiles.php?group_id=87034&package_id=90541&release_id=288585

(It is in the basictypes folder in the latebind.py script by  Mike C.  
Fletcher.) It's so short, I post it for comparison. I'm not really sure  
why there is a run through all possible indices rather than the ones  
that exist in the given "inlist", though.

### Fletcher's
import sys
def flatten(inlist, type=type, ltype=(list,tuple), maxint= sys.maxint):
	"""Flatten out a list, code developed by myself and modified by Tim  
Peters, then by me again :)"""
	try:
		# for every possible index
		for ind in xrange( maxint):
			# while that index currently holds a list
			while isinstance( inlist[ind], ltype):
				# expand that list into the index (and subsequent indicies)
				inlist[ind:ind+1] = list(inlist[ind])
			#ind = ind+1
	except IndexError:
		pass
	return inlist
###


### mine
def flatten(l):
	’’’Flattens a list in place.’’’
	i=0
	while i<len(l):
		while hasattr(l[i],“__iter__”): #used by some ASPN flatteners to  
avoid strings
			l[i:i]=l.pop(i)
		i+=1

###

input: [1, 2, [3, 4, 5, [[6, 7], 8]], ’abc’, 9, [10, 11]]
output:[1, 2, 3, 4, 5, 6, 7, 8, ’abc’, 9, 10, 11]

/c




More information about the Tutor mailing list