Creating new lists from a list of lists
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?
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?
I would not have expected these additional comma's. In the addendum example, I would have liked to have [(1), (2)]
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).
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!)
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).