[Tutor] Multiple lists from single list with nested lists

Kent Johnson kent37 at tds.net
Tue Oct 21 01:36:47 CEST 2008


On Mon, Oct 20, 2008 at 5:33 PM, Sander Sweers <sander.sweers at gmail.com> wrote:
> Hi, I am learning myself python and I need to create 2, or more but
> let's use 2 as an example, lists from a list with nested lists.
>
> For example the below,
>
> ['Test1', 'Text2', ['1', '2'], 'Text3']
>
> Should result in,
>
> [['Test1', 'Text2', '1', 'Text3'],
> ['Test1', 'Text2', '2', 'Text3']
>
> I though of using a temp list and looping over the list twice, something like,
>
> somelist = ['Test1', 'Text2', ['1', '2'], 'Text3']
> templist = []
> for x in range(len(somelist[2])):
>    templist.append([somelist[0], somelist[1], somelist[2][x], somelist[3]])

Is it always just the third item that is a list? If so I think your
solution is not too bad. You could write it as
templist = []
for x in somelist[2]):
   templist.append(somelist[0:2] + [x] + somelist[3:])

or use a list comprehension:
templist = [ somelist[0:2] + [x] + somelist[3:] for x in somelist ]

Kent


More information about the Tutor mailing list