A query about list
Dave Benjamin
ramen at lackingtalent.com
Thu Oct 9 16:05:08 EDT 2003
In article <pan.2003.10.09.19.55.31.536797 at softhome.net>, Santanu Chatterjee wrote:
> I am very new to python. I have a query about
> list in python.
>
> Suppose I have a list
> a = [1,[2,3,4],5,6,7,[8,9,10],11,12]
> I want to know if there is any simple python
> facility available that would expand the above list
> to give
> a = [1,2,3,4,5,6,7,8,9,10,11,12]
>
> I know I can do that with a type() and a for/while loop,
> but is there any simpler way?
Normally, I'd suggest "reduce(operator.add, ...)" to flatten a list, but
since you've got some "naked" entries, that won't work...
I don't know if you consider this simpler, but you could define a reduction
function that checks the type of the second argument, and use it like this:
>>> def merge(x, y):
... if type(y) is type([]): return x + y
... return x + [y]
...
>>> reduce(merge, a, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Dave
--
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
More information about the Python-list
mailing list