Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an if inside a for-loop run only once?

I am trying to put items from two lists together, based on a condition, to create a third list as output. Even though I am a novice, this is relatively straightforward. However, I am trying to make one part of the loop run only once and this where I struggle. Is there a way to do this?

The data comes from a large DataFrame of text data. But I created a simplified version of the problem, to try and solve it more easily (without luck):

a = [1, 2, 3, 4, 5]
A = [4, 5]

b = []
for i in a:
    if i in A:
        b.append(3.5) # My aim is to make this line run only once
        b.append(i)
    else:
        b.append(i)
print(b)

This gives:

[1, 2, 3, 3.5, 4, 3.5, 5]

How can I get the following result?

[1, 2, 3, 3.5, 4, 5]
like image 818
twhale Avatar asked Dec 08 '22 14:12

twhale


2 Answers

You can add a Boolean value that is initialised to false and is then set to true directly after b.append(3.5) is run. If you check this value in the if statement it will only run once.

a = [1, 2, 3, 4, 5]
A = [4, 5]

b = []

ran = False
for i in a:
    if i in A and not ran:
        b.append(3.5) # My aim is to make this line run only once
        ran = True
        b.append(i)
    else:
        b.append(i)
print(b)
like image 194
Lucas Amos Avatar answered Dec 10 '22 04:12

Lucas Amos


You could add a boolean flag for this:

a = [1, 2, 3, 4, 5]
A = [4, 5]

b = []
extend = True
for i in a:
    if i in A:
        if extend:
            b.append(3.5) # My aim is to make this line run only once
            extend = False
        b.append(i)
    else:
        b.append(i)
print(b)

Edit: Actually, if your loop is really that simple, the other answers are more elegant, since except for the first execution, the if and else clauses are equal. If they are not, however, my code is the way to go.

like image 24
Dux Avatar answered Dec 10 '22 02:12

Dux