Easier flow control in Python

1.1k Views Asked by At

In the following code I'm trying to check if the variable "new_shape" already exists within "shape_list". If it does not exist already, I want to add it; if it does exist, I just want to leave it. So far, I have only achieved this using flags. I'm sure there's a way to accomplish the same thing more efficiently without flags. Any suggestions? Thanks for any help you give!

    flag = 0
    for shape in shape_list:
        if new_shape == shape:
            flag = 1
            break
    if flag == 0:
        shape_list.append(new_shape)
3

There are 3 best solutions below

5
On

You can use

if new_shape not in shape_list:
    shape_list.append(new_shape)
4
On

And for an answer that preserves the original flow (although is usually less efficient than the other answer):

for shape in shape_list:
    if new_shape == shape:
        break
else:
    shape_list.append(new_shape)
0
On

If order is not import, you might be able to use a set (documentation).