Dave Matthew - 1 year ago 56

Python Question

Here's an excerpt from my code!

`division = ["Division","Divide","/","div"]`

multiplication =["*","x","times","multiply","multiplication","multiple"]

subtraction = ["-",'minus','subtract','subtraction']

addition = ['+','plus','addition','add']

root = ['root','squareroot','square root']

square = ['square','squared','power 2']

choice = input('calculation type')

print(choice == (division or multiplication or subtraction or addition))

So far, it only gives "False".

How can I check if a variable exists in multiple lists?

I've tried to make lists inside of lists but I still get "False", Here's the code of that...

`division = ["Division","Divide","/","div"]`

multiplication = ["*","x","times","multiply","multiplication","multiple"]

subtraction = ["-",'minus','subtract','subtraction']

addition = ['+','plus','addition','add']

root = ['root','squareroot','square root']

square = ['square','squared','power 2']

basic_double = [division,multiplication,subtraction,addition]

basic_single = [root,square]

choice = input('calculation type')

print(choice == basic_double or basic_single)

Any help would be appreciated! :D thank you!!!

Answer Source

Test whether the `choice`

is in `any`

of the lists:

```
any(choice in ls for ls in [division, multiplication, subtraction, addition])
```

`any`

returns True if at least one of the elements of the given iterable are truthy.

`choice in ls`

tests whether choice is an element of the list.

`choice in ls for ls in [division, multiplication, subtraction, addition]`

is a generator comprehension, meaning it's an iterator that returns the result of `choice in ls`

for any possible `ls`

in `[division, multiplication, subtraction, addition]`

.

If *one* of those lists contains the `choice`

, `any`

will return True, False otherwise.