Thursday, September 15, 2011

How to turn a list outside-in



def turnListOutsideIn(aList):
	"""
	Returns a new list containing the 1st element, then the last,
	then the 2nd, then the next-to-last, etc.
	"""

	# create a reversed copy of the original list
	revList = list(aList)
	revList.reverse()

	# zip them together as a list of tuple pairs
	zippedList = zip(aList, revList)

	# flatten the list
	flatList = [inner for outer in zippedList for inner in outer]

	# return the first half of the list
	return flatList[0:len(aList)]


digits = range(10)
 
print outsideInList(digits)
[0, 9, 1, 8, 2, 7, 3, 6, 4, 5]

No comments:

Post a Comment