Nono.MA

Python "in" and "not in" operators

JULY 17, 2022

Here's an example on how to use the "in" and "not in" Python operators.

› python
Python 3.9.13 (main, May 24 2022, 21:28:31) 
[Clang 13.1.6 (clang-1316.0.21.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> names = ['James', 'Paul', 'Lily', 'Glory']
>>> names
['James', 'Paul', 'Lily', 'Glory']
>>> print('YES' if 'Lily' in names else 'NO')
YES
>>> print('YES' if 'John' in names else 'NO')
NO
>>> print('NO' if 'Lily' not in names else 'YES')
YES
>>> print('NO' if 'John' not in names else 'YES')
NO

You could use this as a conditional in your code.

names = ['James', 'Paul', 'Lily', 'Glory']
new_person = 'Nono'

if new_person not in names:
  names.append(new_person)
  print(f'Added {new_person} to names.')
  # Added Nono to names.

if new_person in names:
  print(f'{new_person} was correctly added to names.')
  # Nono was correctly added to names.

BlogCodePython