Menu
CoddyTech

Content Versus Object Identity

Lesson 8 of 48 in Coddy's Python for C Developers course.

C compares string contents with a function such as strcmp. Comparing pointers asks whether addresses compare equal, not whether the character sequences match. Python strings and lists implement value equality through ==, while is asks whether both operands identify the same object. The C arrays here are separate live objects, as are the two Python lists. Use == for text and is None for absence. Ordinary user-defined Python classes initially use identity-based equality unless they implement a comparison protocol.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    char a[] = "red"; char b[] = "red";
    printf("%d %d\n", strcmp(a, b) == 0, &a[0] == &b[0]);
    return 0;
}

Python: complete example.py

a = ["red"]
b = ["red"]
print(a == b, a is b)

Watch the difference

Do not use Python is for small integers or strings. Object reuse can make an identity mistake appear to work, but it is not a content comparison contract.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Two labels arrive on separate lines. Only the reserved word missing represents absence; the scaffold replaces it with None. Empty text is a real label. Print value equality, then whether the first label is absent, then whether the second is absent, as three Python booleans.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

Use Python == for string content, where a C routine would use strcmp; use is None for absence.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler