user17696058
user17696058

Reputation:

For Loop With Different Signs

Can someone explain to me how to shorten this code like with a for loop or something? The if statement doesn't change completely, just the "+" and "-".

# "+" and "-" changes

if (y[0] + 1, y[1]) in p:
    x.append((y[0] + 1, y[1]))
    p.remove((y[0] + 1, y[1]))

if (y[0] - 1, y[1]) in p:
    x.append((y[0] - 1, y[1]))
    p.remove((y[0] - 1, y[1]))
...

Upvotes: 1

Views: 196

Answers (2)

user23952
user23952

Reputation: 682

for s in [+1, -1]:
    if (y[0] + s, y[1]) in p:
        x.append((y[0] + s, y[1]))
        p.remove((y[0] + s, y[1]))

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54698

for delta in (-1, 1):
    if (y[0] + delta, y[1]) in p:
        x.append((y[0] + delta, y[1]))
        p.remove((y[0] + delta, y[1]))

Upvotes: 1

Related Questions