×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Membership Operators (Use, Syntax, and Examples)

By IncludeHelp Last updated : December 08, 2024

Python Membership Operators

Python Membership Operators are the operators, which are used to check whether a value/variable exists in the sequences like string, list, tuples, sets, dictionary or not.

These operator returns either True or False, if a value/variable found in the list, its returns True otherwise it returns False.

Python Membership Operators: in, not in

Operator Description Example
in It returns True, if a variable/value found in the sequence. 10 in list1
not in It returns True, if a variable/value does not found in the sequence. 10 not in list1

1. Python 'in' Operator

The "in" operator returns True, if a variable/value found in the sequence.

Syntax

Below is the syntax of "in" operator:

10 in list1

Python 'in' Operator Example

# Python example of "in" operator

# declare a list and a string
str1 = "Hello world"
list1 = [10, 20, 30, 40, 50]

# Check 'w' (capital exists in the str1 or not
if "w" in str1:
    print("Yes! w found in ", str1)
else:
    print("No! w does not  found in ", str1)

# check 30 exists in the list1 or not
if 30 in list1:
    print("Yes! 30 found in ", list1)
else:
    print("No! 30 does not found in ", list1)

Output

Yes! w found in  Hello world
Yes! 30 found in  [10, 20, 30, 40, 50]

2. Python 'not in' Operator

The "not in" operator returns True, if a variable/value does not found in the sequence.

Syntax

Below is the syntax of "not in" operator:

10 not in list1

Python 'not in' Operator Example

# Python example of "not in" operator

# declare a list and a string
str1 = "Hello world"
list1 = [10, 20, 30, 40, 50]

# check 'X' (capital) exists in the str1 or not
if "X" not in str1:
    print("yes! X does not exist in ", str1)
else:
    print("No!  X exists in ", str1)

# check 90 exists in the list1 or not
if 90 not in list1:
    print("Yes! 90 does not exist in ", list1)
else:
    print("No! 90 exists in ", list1)

Output

yes! X does not exist in  Hello world
Yes! 90 does not exist in  [10, 20, 30, 40, 50]

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.