House Prophet
House Prophet

Reputation: 11

am trying to convert this for loop into list comprehension?

L=[]
for i in range(11):
     L.append(1)
     for z in range(i):
        L.append(0)
L.append(1) #this is to add a 1 at the end of list
print(L)

Upvotes: 1

Views: 34

Answers (1)

CDJB
CDJB

Reputation: 14546

This should give the desired result - for i in the desired range, generate the tuple (1,0,0,0...) and then flatten the list of tuples. Finally, append the trailing 1.

>>> [x for i in range(11) for x in (1,)+(0,)*i] + [1]
[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

Upvotes: 1

Related Questions