Skip to content

Python string not in list

  • by

You can use Python in operator or not in operator to check if a string is not present in the list. The cheapest and most readable solution is using the in operator (or in your specific case, not in)

Python string not in the list

Simple example code.

The operator not in is defined to have the inverse true value of in.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']

# string in the list
if 'A' in l1:
    print('A is present in the list')

# string not in the list
if 'X' not in l1:
    print('X is not present in the list')

Output:

Python string not in the list

Using Python f-strings with user input

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = input('Please enter a character A-Z:\n')

if s in l1:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')

Using count()

The count() function to get the number of occurrences of a string in the list. Zero means that string is not present in the list.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'

count = l1.count(s)
if count > 0:
    print(f'{s} is present in the list for {count} times.')

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *