# [Chicago] Resolving lists within lists within lists within .....

Joshua Herman zitterbewegung at gmail.com
Mon Feb 15 22:09:33 EST 2016

```The idea of flattening a object or datatype is a functional programming technique and not just a part of Ruby and Mathematica According to this answer on the programming stack exchange there is no method / function that implements flatten for build in Python functions but you can get almost there with itertools.chain.from_iterable . See http://programmers.stackexchange.com/questions/254279/why-doesnt-python-have-a-flatten-function-for-lists .
> On Feb 15, 2016, at 4:12 PM, Lewit, Douglas <d-lewit at neiu.edu> wrote:
>
> Hi everyone,
>
> Well it's President's Day and I've got the day off!  Hooray!!!  Finally some time to just relax and mess around.  So I'm at my computer playing around with Python and wondering how to resolve the issue of multiple lists embedded within other lists.  I came up with two functions that I think solve the problem.  But I was wondering if Guido or someone else added a builtin function or method that does this automatically for the programmer.  Or is there an easier way?  Okay.... thanks.  ( In case you're wondering why I called the function "flatten" it's because I know from experience that Wolfram Mathematica and Ocaml have these "flatten" functions.  I think Ruby has something similar, but I haven't played with Ruby in a while so I'm not really sure. )  The try: except block is important because you can't subscript non-list data structures in Python.  The IndexError is what you get when you try to index an empty list.  So I ****think**** my try: except block covers most commonly encountered exceptions when working with lists embedded within other lists.
>
> Best,
>
> Douglas.
>
> def flatten(lst):
> 	if lst == [ ]:
> 		return lst
> 	else:
> 		try:
> 			return [lst[0][0]] + flatten(lst[0][1:] + lst[1:])
> 		except TypeError:
> 			return [lst[0]] + flatten(lst[1:])
> 		except IndexError:
> 			return flatten(lst[1:])
>
> def flattenAgain(lst):
> 	newList = lst[:]
> 	while newList != flatten(newList):
> 		newList = flatten(newList)
> 	return newList
>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20160215/2a302f43/attachment.html>
```