Search code examples
pythonlistnestedlist-comprehension

How to make the length of a nested list equal to the value of a number in a list, using list comprehension?


I'm really new to Python, so forgive me if this is a ridiculously simple question. I have a given list

x = [0,1,2,3,4,5,6,7,8,9]

Now I want to make a list e, using list comprehension, that contains a list for each odd element of list x. All inner elements of this list should be true and the number of list elements is given by the current number of x. So it should look like this:

[[], [True, True], [True, True, True, True], ...]

The code I have so far is:

e = [[True for z in x] for z in x if z % 2 != 0]

When printed I get a list, where the amount of nested lists is equal to the amount of odd numbers in list x, but all of them contain True ten times. What do I have to do to make the lengths of the inner lists equal to the values of the odd numbers?


Solution

  • This code should do what you want:

    [[True for _ in range(z)] for z in x if z % 2 != 0]
    

    The difference is in the inner comprehension, [True for _ in range(z)].

    Previously, you were iterating over each z in x - so, for each iteration, z is an integer out of x. Then, for each unique z, you were iterating over the entire x again. Since x has 10 elements, that gives you 10 iterations.

    Instead, what you want to do is produce an array of [True] with length z. range(z) gives you a guaranteed iterable of length z for which you can generate as many Trues as you need.

    The innermost variable name, I replaced with a _, because it isn't used.