Home > Software design >  Repeating a certain line several times based on the length of a list in Python
Repeating a certain line several times based on the length of a list in Python

Time:08-29

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]

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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]
  • Related