Skip to content
Advertisement

How to continue for loop until it meets condition? [closed]

I want to looping until it meets the condition. In this case i want to continue till List_list looks like

["one","one","two","two","three","three","four","four","five","five","six","seven","eight","nine","ten"]  


lst =["one","two","three","four","five","six","seven","eight","nine","ten”]
List_list = list()    
for rn in lst:
    List_list.append(rn)
    if 15 == len(List_list):
        break

Advertisement

Answer

Ask #2:

Solution to repeat first 5 items, then single instance of next 5 items

lst =["one","two","three","four","five","six","seven","eight","nine","ten"]
List_list = []
for i in range(10):
    List_list.append(lst[i])
    if i < 5:
        List_list.append(lst[i])

print (List_list)

The output of this will be:

['one', 'one', 'two', 'two', 'three', 'three', 'four', 'four', 'five', 'five', 'six', 'seven', 'eight', 'nine', 'ten']

If you are looking for a single line answer using list comprehension, then you can use this.

List_list = [y for x in lst[:5] for y in [x,x]] + [x for x in lst[5:]]
print (List_list)

Output is the same:

['one', 'one', 'two', 'two', 'three', 'three', 'four', 'four', 'five', 'five', 'six', 'seven', 'eight', 'nine', 'ten']

Ask #1:

Solution for earlier question: Add 15 items to a list: All 10 items from original list + first from original list

You can do something as simple as this:

List_lst = lst + lst[:5]
print (List_lst)

If you still insist on using a for loop and you want 15 items, then do this and it will give you same output.

List_list = list()
for i in range(15):
    List_list.append(lst[i%10])
    
print (List_list)

A list comprehension version of this will be:

List_list = [lst[i%10] for i in range(15)]

print (List_list)

If you want to fix your code with a while loop, see the details below.

Convert the for loop to while True:. Start iterating using a counter i and check for mod of 10 to get the position to be inserted.

lst = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]

List_list = list()
i = 0
while True:
    List_list.append(lst[i%10])
    i+=1
    if len(List_list) == 15:
        break

print (List_list)

This will result in

["one", "two", "three",  "four",  "five", "six", "seven", "eight", "nine", "ten", "one", "two", "three",  "four",  "five"]  
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement