Reputation: 41
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)
Upvotes: 1
Views: 1163
Reputation: 22001
If order is not import, you might be able to use a set
(documentation).
Upvotes: 0
Reputation: 798626
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)
Upvotes: 2
Reputation: 856
You can use
if new_shape not in shape_list:
shape_list.append(new_shape)
Upvotes: 6