Built with Tutify.io

    AIStudyLabs

    Assignment, Identity, and Membership Operators

    Assignment, Identity, and Membership Operators

    Introduction

    In this lesson you will deepen your understanding of Python by working with three powerful operator families that control how variables are updated and how objects are compared and searched:

    You will also learn to avoid subtle bugs that come from confusing assignment, identity, equality, and membership in real code.


    1. Assignment and Augmented Assignment Operators

    You already know the basic assignment operator =. Python also provides augmented assignment operators that update variables in place, making code shorter and often clearer.

    1.1 Basic vs augmented assignment

    # Basic assignment and update
    count = 0
    count = count + 5
    
    # Equivalent using augmented assignment
    count2 = 0
    count2 += 5
    
    print("count =", count)
    print("count2 =", count2)
    
    # Output
    count = 5
    count2 = 5
    

    Explanation:

    1.2 Common augmented assignment operators

    x = 10
    
    x += 3   # x = x + 3 → 13
    x -= 2   # x = x - 2 → 11
    x *= 4   # x = x * 4 → 44
    x /= 2   # x = x / 2 → 22.0 (note: becomes float)
    
    print(x)
    
    # Output
    22.0
    

    Key points:

    1.3 Augmented assignment with mutable objects

    Augmented assignment can behave differently depending on whether the object is mutable.

    nums = [1, 2]
    
    # Augmented assignment on a list
    nums += [3, 4]
    
    print(nums)
    
    # Output
    [1, 2, 3, 4]
    

    Explanation:


    2. Identity vs Equality in Python

    Python has two different concepts for comparing things:

    2.1 Equality vs identity basics

    a = [1, 2, 3]
    b = [1, 2, 3]
    c = a
    
    print(a == b)   # same contents?
    print(a is b)   # same object?
    print(a is c)   # same object?
    
    # Output
    True
    False
    True
    

    Explanation:

    2.2 Identity with small integers and strings

    CPython (the main Python implementation) interns some immutable objects (like small integers and some strings) for efficiency. This can make identity comparisons look surprising.

    x = 10
    y = 10
    
    print(x == y)  # same value
    print(x is y)  # often True for small ints
    
    s1 = "hello"
    s2 = "hello"
    
    print(s1 == s2)
    print(s1 is s2)  # may be True due to interning
    
    # Possible Output (typical CPython)
    True
    True
    True
    True
    

    Important:

    2.3 Identity and mutability

    With mutable objects, identity is more visible because mutations affect all references to the same object.

    nums1 = [1, 2]
    nums2 = nums1   # both refer to the same list
    
    nums1.append(3)
    
    print(nums1)
    print(nums2)
    print(nums1 is nums2)
    
    # Output
    [1, 2, 3]
    [1, 2, 3]
    True
    

    Explanation:

    2.4 Correct uses of is

    Use is only when you explicitly care about object identity, most commonly with singletons like None:

    value = None
    
    if value is None:
        print("No value provided")
    
    # Output
    No value provided
    

    3. Membership Operators: in and not in

    Membership operators check whether a value appears inside another object, such as a list, string, tuple, set, or dictionary.

    3.1 Membership in lists and strings

    fruits = ["apple", "banana", "cherry"]
    text = "python programming"
    
    print("banana" in fruits)
    print("pear" not in fruits)
    print("python" in text)
    print("thon" in text)
    
    # Output
    True
    True
    True
    True
    

    Explanation:

    3.2 Membership in dictionaries

    For dictionaries, in checks keys, not values.

    user = {
        "username": "alice",
        "age": 30,
        "active": True,
    }
    
    print("username" in user)   # key membership
    print("alice" in user)      # values are NOT checked by default
    print("alice" in user.values())  # explicit value check
    
    # Output
    True
    False
    True
    

    Explanation:

    3.3 Practical example: login and permissions

    allowed_users = ["alice", "bob", "carol"]
    
    username = "bob"
    
    if username in allowed_users:
        print("Access granted for", username)
    else:
        print("Access denied")
    
    # Output
    Access granted for bob
    

    Explanation:


    4. Avoiding Common Operator Bugs

    Misusing assignment, identity, equality, and membership leads to subtle, hard-to-find bugs. Here are patterns to watch for.

    4.1 Confusing = and ==

    # Incorrect (and invalid syntax in Python)
    # if x = 5:  # This will raise a SyntaxError
    #     ...
    
    # Correct
    x = 5
    if x == 5:
        print("x is five")
    
    # Output
    x is five
    

    Use = only for assignment, == for comparison.

    4.2 Using is instead of ==

    score = 100
    
    # Wrong style: may behave inconsistently across implementations
    if score is 100:
        print("Perfect score (using is)")
    
    # Correct
    if score == 100:
        print("Perfect score (using ==)")
    
    # Possible Output
    Perfect score (using is)
    Perfect score (using ==)
    

    Explanation:

    4.3 Misunderstanding dictionary membership

    settings = {"theme": "dark", "debug": False}
    
    # Buggy intention: check if debug mode is set to False
    if False in settings:
        print("Debug explicitly disabled")
    else:
        print("Checking value correctly...")
    
    if settings.get("debug") is False:
        print("Debug explicitly disabled (correct check)")
    
    # Output
    Checking value correctly...
    Debug explicitly disabled (correct check)
    

    Explanation:


    Summary / Key Takeaways

    In this lesson on Assignment, Identity, and Membership Operators, you have learned:

    Python Programming – Complete Course with Practical Examples — Operators, Expressions, and Control Flow

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found