None and Identity
Concepts covered: Data Types
Sometimes a variable needs to exist but doesn't have a meaningful value yet. Maybe you're waiting for data to arrive, or a search found nothing. Python has a special value for this: None.
None marks the absence of a value
None is Python's way of representing "no value" or "nothing." Zero is a number and "" is still a string, but None means the complete absence of a value.
result = None
user = find_user_by_email("test@example.com")You might use None as a placeholder, or a function might return None to indicate "not found."
Functions return None by default
In Python, if a function doesn't explicitly return a value, it automatically returns None. Consider a function that just prints something:
def greet(name):
print("Hello, " + name)
result = greet("Maya")
print(result)Output:
Hello, Maya None
greet prints its greeting but does not return anything, so result becomes None.
Checking for None
Use is to check for None:
if result is None:
print("No result found")
if user is not None:
print("Found user: " + user.name)Why "is" Instead of "=="?
The == operator checks if two values are equal. The is operator checks if two variables refer to the exact same object in memory.
- Do
- result is None
- value isn't None
- if user is None: handle()
- Avoid
- result == None
- value != None
- if not user: handle()
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b)
print(a is b)
print(a is c)Output:
True False True
a == b is True (same values). a is b is False (different objects). a is c is True (same object).
None is the correct signal for "no value here." Functions that search for something and fail, or optional parameters that were not provided, return or default to None.
The is None check is standard Python convention, and the standard library uses it throughout.
About this lesson
This section is part of the Python Expressions: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.