Repeating a certain line several times based on the length of a list in Python

Question:

I want to repeat the line A=A[:1] + [i + 1 for i in A] several times based on the length of B. For instance, len(B)=4 and A=A[:1] + [i + 1 for i in A] has been repeated 4 times. Is there a way to repeat A=A[:1] + [i + 1 for i in A] without writing it explicitly and get the same current output?

A=[0,1,2,3,4,5,6,7]  
B=[1,3,6,7]          

A=A[:1] + [i + 1 for i in A]
A=A[:1] + [i + 1 for i in A]
A=A[:1] + [i + 1 for i in A]
A=A[:1] + [i + 1 for i in A]
print(A)

The current output is

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Asked By: user19862793

||

Answers:

Try this,

A=[0,1,2,3,4,5,6,7]  
B=[1,3,6,7]          

for i in range(len(B)+1):
  A=A[:1] + [i + 1 for i in A]
  print(A)
Answered By: Nirali
A=[0,1,2,3,4,5,6,7]  
B=[1,3,6,7]          
x = 0
while x < len(B):
    A=A[:1] + [i + 1 for i in A]
    x = x + 1

print(A)

While condition is not met, the loop will continue.

In this case, x being less than the length of B – which is to say how many items are in it.

Answered By: Kennetic

You can simply do a for loop over B (ignoring the actual values in B since they don’t matter):

>>> A=[0,1,2,3,4,5,6,7]
>>> B=[1,3,6,7]
>>> for _ in B:
...     A = A[:1] + [i + 1 for i in A]
...
>>> print(A)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Answered By: Samwise

Try this:

for j in range(len(B)):
A = A[:1] + [i + 1 for i in A]

Then just print normally after the for loop.

Answered By: Sami Walid
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.