can we append a list with another list in Python ?

Joshua Landau joshua.landau.ws at gmail.com
Tue Oct 23 16:06:43 EDT 2012


On 23 October 2012 21:03, Joshua Landau <joshua.landau.ws at gmail.com> wrote:

> On 23 October 2012 12:07, Jean-Michel Pichavant <jeanmichel at sequans.com>wrote:
>
>> ----- Original Message -----
>>
>> > Thankyou.. but my problem is different than simply joining 2 lists
>> > and it is done now :)....
>>
>>
>> A lot of people though you were asking for joining lists, you description
>> was misleading.
>>
>> I'll take a guess: you want to flatten a list of list.
>> "Nested" list comprehensions can do the trick.
>>
>> aList =[[1,5], [2,'a']]
>> [item for sublist in aList for item in sublist]
>>
>> ...
>> [1, 5, 2, 'a']
>>
>> I find it rather difficult to read though.
>
>
> We have a library function for this, in the one-and-only itertools.
>
> >>> listoflists = [list(range(x, 2*x)) for x in range(5)]
>> >>> listoflists
>> [[], [1], [2, 3], [3, 4, 5], [4, 5, 6, 7]]
>> >>> from itertools import chain
>>  >>> list(chain.from_iterable(listoflists))
>> [1, 2, 3, 3, 4, 5, 4, 5, 6, 7]
>
>
> It does exactly what it says... fast and easy-to-read.


Note that I think what he really wanted is to go from

a, b, c = [list(x) for x in (range(10), range(11, 20), range(21, 30))]

to

> list(range(30))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121023/a6cd1748/attachment.html>


More information about the Python-list mailing list