Ask Your Question
0

Creating new lists from a list of lists

asked 2014-09-02 10:50:38 +0100

this post is marked as community wiki

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 flag offensive close merge delete

Comments

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?

slelievre gravatar imageslelievre ( 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)]

ayyer gravatar imageayyer ( 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).

slelievre gravatar imageslelievre ( 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!)

ayyer gravatar imageayyer ( 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).

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

1 Answer

Sort by ยป oldest newest most voted
2

answered 2014-09-02 11:44:12 +0100

slelievre gravatar image

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)]
edit flag offensive delete link more

Comments

Thanks, that's perfect!

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

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2014-09-02 10:50:38 +0100

Seen: 1,024 times

Last updated: Sep 16 '14