Concatenating a list of lists

Hans Nowak wurmy at earthlink.net
Sat Aug 17 22:21:15 CEST 2002


Neophytos Michael wrote:
> A quick question for the python experts.  I have a list of lists (only
> one level) that I want to turn into a flat list.  What's the python
> way of achieving this?  I came up with:
> 
> def red_aux(l1, l2):
>     l1.extend(l2);
>     return l1;
> 
> dest_list = reduce(red_aux, src_list, []);

You're using a functional approach, which works OK. Another approach would be, 
looping over the list-with-sublists:

 >>> x = [range(5), range(3), [6,7,8]]
 >>> y = []
 >>> for seq in x:
	y.extend(seq)
	
 >>> y
[0, 1, 2, 3, 4, 0, 1, 2, 6, 7, 8]

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.angelfire.com/jazz/aquila/blog/blogger.html




More information about the Python-list mailing list