views:

331

answers:

3

I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this:

[[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)]

so it should return something like:

[[1,1,1],
 [1,1,1],
 [2,2,2]]

How might I go about doing this?

Thanks for your help.

+4  A: 

It appears as though you're looking for something like this:

[[1 if j <= 1 else 2 for i in range(3)] for j in range(3)]

The Python conditional expression is a bit different from what you might be used to if you're coming from something like C or Java:

The expression x if C else y first evaluates C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

A slightly shorter way to do the same thing is:

[[1 if j <= 1 else 2]*3 for j in range(3)]
Greg Hewgill
This is good since I can easily scale by changing the size of the range and change the conditional statement. Thanks!
Casey
+8  A: 

Greg's response is correct, though a much simpler and faster expression to produce your desired result would be

[[j] * 3 for j in (1, 1, 2)]

i.e., remember that for need not apply to a range only;-), list-multiplication exists, and so on;-).

Alex Martelli
I like this answer, neat
Juparave
Does this allow the table to still be mutable? say I want to change [0][0] to 10, will that change any of the other values?
Casey
@Casey — No, it won't change any of the other values.
Ben Blank
@Casey, @Ben is correct, each sublist is a distinct object (since they're made within a list comprehension).
Alex Martelli
+1  A: 

Try that

>>> [[(1 if j<1 else 2) for i in range(3)] for j in range(3)]
[[1, 1, 1], [2, 2, 2], [2, 2, 2]]

The second time j=1 so j<1 fails

Juparave