Home > OS >  How to check if a value is in allowlist?
How to check if a value is in allowlist?

Time:12-16

exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]

How could repeat the number of times in exampleArray[0] until the end of the array that alse checks if that value is in allowedItems?

I have tried this but it doesnt work:

for x in exampleArray[0]:
    if exampleArray[x] in allowedItems:
        print("Valid Item")

please send example code

CodePudding user response:

for x in exampleArray:
    if x in allowedItems:
        print(f"{x} is a valid Item")

CodePudding user response:

exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]
for x in exampleArray:
    if x in allowedItems:
        print("Valid Item: " str(x))
    else:
        print("Invalid Item: " str(x))

Output:-

Invalid Item: 2
Valid Item: a
Valid Item: b

CodePudding user response:

# Another way: You can use set()

exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]

# Just want to know allowed list items
# intersection and '&' is same
set(allowedItems).intersection(set(exampleArray))
set(allowedItems) & set(exampleArray)

# Print allowed items list
[ print(x ' is Allowed') for x in set(allowedItems).intersection(set(exampleArray)) ]
[ print(x ' is Allowed') for x in set(allowedItems) & set(exampleArray) ]

CodePudding user response:

I think you are trying to achieve this.

example_array = [2, "a", "b"]
allowed_items = ["a", "b"]
for _ in range(example_array[0]):
    for item in example_array[1:]:
        if item in allowed_items:
            print(f"{item} is in allowed items")

The loop will be iterated examle_array[0] number of times like in the case above 2 times and then for each item, except the first one (example_array[0] - 2 ), check if the item is in allowed_list.

Below is the output:

a is in allowed list
b is in allowed list
a is in allowed list
b is in allowed list
  • Related