1

I have a list of integers x, and I want to create a 2D jagged list y of zeros, such that the length of row i of y is determined by element i of x.

For example:

x = [1, 3, 4]

Then:

y = [[0], [0, 0, 0,], [0, 0, 0, 0]]

How can I do this?

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

2 Answers2

2

Try this one-liner:

x = [1, 3, 4]
y = [[0]*s for s in x]

Now y will contain the expected value:

y
=> [[0], [0, 0, 0], [0, 0, 0, 0]]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

You can use a list comprehension, but you want to avoid making the sublists using the multiplication operator, e.g.:

[0] * 5    # will produce 'undesired' behavior (see the above link)

One way to do it would be the following

>>> x = [1, 3, 4]
>>> [[0 for _ in range(i)] for i in x]
[[0], [0, 0, 0], [0, 0, 0, 0]]
Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    Using the `*` operator is a problem only if we reuse the same sublists (example: `[[0, 0]]*2`), if we create a different sublist for each row (as shown in my answer) the problem you describe won't happen – Óscar López Aug 14 '14 at 16:21