# Creating new lists from a list of lists

This post is a wiki. Anyone with karma >750 is welcome to improve it.

I have a newbie question about list comprehension. Suppose I have a list of lists as follows.

A = [[1, 2], [3], [4, 5]]


I want to create all possible lists by choosing exactly one element from each list. Is there a quick way of doing that? In other words, I want the program to return the following for A:

[[1,3,4],[1,3,5],[2,3,4],[2,3,5]]


I can do this if the length of A is 3, for instance. But I want to include this in a program where the length of the list A is an input and the sublists are created from the input. Is there a quick way to do this?

Addendum: I just realised that this doesn't work when A is a list of length 1. See the example below.

sage: A = [[1, 2]]
sage: list(itl.product(*A))
[(1,), (2,)]


I am taking care of this separately right now, but is there a way to include this case too?

edit retag close merge delete

About your addendum: to me, your new example seems to show that it also works for a list of length one. What result did you expect?

( 2014-09-16 20:24:55 +0100 )edit

I would not have expected these additional comma's. In the addendum example, I would have liked to have [(1), (2)]

( 2014-09-17 07:52:47 +0100 )edit

In Python, (1) is the same as 1, and a 1-tuple is entered and displayed with a comma. This makes sense and allows to distinguish for example between (3+2)*4 and (3+2,)*4 (try those in Sage).

( 2014-09-17 11:02:53 +0100 )edit

Oh I see! I had an error in my program in this case, but that was probably for some other reason. Thanks for the clarification. (The hanging comma's make the expression look strangely incomplete though!)

( 2014-09-17 14:38:01 +0100 )edit

Or maybe it's (1, 2, 3) which looks incomplete. In Python you can also enter it as (1, 2, 3,) but in the output it's displayed in the usual "incomplete" form (1, 2, 3).

( 2014-09-17 16:38:06 +0100 )edit

Sort by ยป oldest newest most voted

You can use itertools.product, as follows:

sage: A = [[1, 2], [3], [4, 5]]
sage: import itertools as itl
sage: list(itl.product(*A))
[(1, 3, 4), (1, 3, 5), (2, 3, 4), (2, 3, 5)]

more

Thanks, that's perfect!

( 2014-09-03 10:52:34 +0100 )edit