Membership Operators in Python | Python Tutorials for Beginners #lec19
Understanding Membership Operators in Python
Introduction to Membership Operators
- The video discusses membership operators in Python, following a previous discussion on identity operators.
- The presenter poses a question about checking if a character exists within a string, using "Jenny" as an example.
Functionality of Membership Operators
- Instead of using loops to check each character, membership operators allow for simpler checks.
- There are two types of membership operators:
inandnot in, used to determine the presence of characters or substrings in sequences like strings, lists, tuples, and dictionaries.
Practical Examples with Strings
- Membership operators check if a character or substring is present in a sequence; for instance, checking if 'y' is in "Jenny".
- Using the expression
Y in Strwill return true if 'y' is found; otherwise, it returns false.
Understanding in and not in
- An example shows that checking for 'Y' (uppercase) returns false since it's not present.
- Conversely, using
not inconfirms that 'Y' is indeed not part of the string.
Additional Examples with Lists
- The presenter introduces lists as another context for membership operators. For example, checking if 10 is present in a list
[1, 10, -1].
- If 10 is checked with
not in, it will return false because it exists within the list.
Practical Implementation
- A practical coding demonstration begins where the presenter creates a file named
membership_operator.py.
- Various checks are performed on strings and lists to illustrate how membership operators function effectively. For instance:
- Checking lowercase 'j' against "Jenny Khatri" returns false due to case sensitivity.
This structured approach provides clarity on how membership operators work within Python programming through both theoretical explanations and practical examples.
Understanding Membership Operators in Python
Basic Concepts of Membership Operators
- The speaker explains that when checking for membership in a list, there is no need to use single quotes around numbers since they are not strings.
- An example is provided where checking if
20is in the listL1returnsFalse, demonstrating how membership checks work.
- The speaker comments out previous code and checks if
20is not inL1, which correctly returnsTrue.
- A check for
-7not being inL1results inFalse, indicating that it is indeed present within the list.
- The speaker concludes by emphasizing the basic idea behind membership operators, reinforcing understanding of their functionality.