I need to find if an integer is found in a list of strings.
context = ['4', '6', '78']
if category.id in context:
The code above is not working because I compare int(category id) with strings.
I can't use int(context) because context is a list and will give an error.
I can convert category.id to string, but can bad situations appear ?
Using in
operator it is possible to convert the strings to int, or I need to use a for loop
?
You could also consider using a list comprehension to convert context
to a list of integers.
context_ints = [int(i) for i in context]
if category.id in context_ints:
... do stuff ...
If context
is guaranteed to be a list of strings that can sensibly be converted to integers, this may be the safest route for you.