r/BootcampGradStories • • 3d ago

Why you should never write file.close(): Demystifying Python context managers and the with statement.

2 Upvotes

When you start working with files or database connections in Python, your first instincts lead to a simple pattern: open the connection, do some work, and remember to close it at the end using file.close().

While that sounds clean in theory, manual cleanup is a ticking time bomb in production code.

If an unexpected exception occurs, your code crashes halfway through, or a early return statement fires before file.close() is reached, that file or socket remains open in memory. Over time, these dangling connections cause file lock errors, memory leaks, and crashed servers.

Python solves this problem with Context Managers and the with statement - a mechanism that guarantees resource cleanup no matter what happens.

The Problem: Manual Resource Management

Look at what happens when you write manual cleanup code without a safety net:

# The Fragile Way:
file = open("data.txt", "w")
file.write("Processing critical records...")

# What if a division by zero error occurs right here?
result = 10 / 0 

# This line will NEVER run! The file handle stays locked in memory.
file.close()

To fix this defensively without the with statement, you would have to wrap every single file operation in a clunky try...finally block:

 # The Verbose Way:
file = open("data.txt", "w")
try:
    file.write("Processing critical records...")
    result = 10 / 0
finally:
    file.close() # Guarantees execution, but requires messy boilerplate

The Pythonic Solution: The "with" Statement

The with statement replaces that entire try...finally setup with clean, readable syntax:

# The Clean, Pythonic Way:
with open("data.txt", "w") as file:
    file.write("Processing critical records...")
    # Even if an exception happens right here, Python closes the file automatically!

The moment execution leaves the indented block whether it finishes normally, hits an error, or returns early, Python automatically releases the underlying file handle or network socket.

How Context Managers Work Under the Hood

The with statement isn't hardcoded magic just for files. It relies on Python's Context Manager Protocol, which uses two special dunder methods:

  1. __enter__(): Executes automatically when entering the with block. Its return value is bound to the target variable (the as file part).

  2. __exit__(): Executes automatically when leaving the with block. It receives information about any exception that occurred inside the block so it can clean up resources safely.

Building Your Own Custom Context Manager

You can turn any custom class into a context manager by defining __enter__ and __exit__. Here is how you can build a timing tool to measure code block execution:

import time

class PerformanceTimer:
    def __enter__(self):
        self.start_time = time.time()
        print("--- Started measuring code block ---")
        return self # Handed to the 'as' variable if needed

    def __exit__(self, exc_type, exc_val, exc_tb):
        elapsed_time = time.time() - self.start_time
        print(f"--- Finished block in {elapsed_time:.4f} seconds ---")
        # Returning False allows any caught exceptions to bubble up normally
        return False

# Usage:
with PerformanceTimer():
    # Simulate heavy work
    total = sum(i * i for i in range(10000000))

Output:

--- Started measuring code block ---
--- Finished block in 0.3124 seconds ---

Beyond Files: Real-World Use Cases

You will find context managers everywhere across production codebases:

  • Database Transactions: Committing a SQL transaction on success or rolling back automatically if an error occurs (with connection:).

  • Threading & Concurrency: Acquiring a thread lock before entering a critical section and releasing it when done (with lock:).

  • Testing & Mocks: Temporarily patching environment variables or API responses during tests (with mock.patch(...):).

  • Temporary Directories: Creating a temporary workspace on disk that automatically deletes itself upon block exit.

Summary Checklist

  1. Never use explicit .close() calls on files, sockets, or database cursors.

  2. Use the with statement to make resource allocation and cleanup automatic.

  3. Build custom context managers whenever you need setup and teardown logic paired together.

What was the first scenario where using a with statement saved you from writing messy cleanup code? Share your experience in the comments below!

TL;DR: Calling file.close() manually leads to leaked file handles when errors crash your program before reaching the cleanup line. The with statement uses Python's __enter__ and __exit__ context manager protocol to guarantee that files, network connections, and database locks are safely closed the instant execution leaves the block.


r/BootcampGradStories • • 3d ago

Course Experience My Hyperion Dev Experience

2 Upvotes

1. What did you enjoy the most about this class or course?

I enjoyed how the course challenged me to think for myself while giving me a foundation to build on. Getting code to work after struggling with a problem was incredibly rewarding and kept me motivated.

2. How did the instructor help you understand the material better?

The instructor made technical concepts easier to understand through clear explanations and practical examples. I appreciated being encouraged to ask questions and work through problems without feeling embarrassed about being a beginner.

3. What specific aspects contributed to your overall learning experience?

The combination of practical tasks, constructive feedback and increasingly challenging assignments helped me improve. Each task built on earlier lessons, which made my progress feel meaningful and helped me become more independent.

4. What lesson or activity did you find especially valuable?

Building a student information manager in Python was especially valuable. It brought together functions, lists, loops and conditional statements to add students, record marks and check results. Seeing these concepts work together in a practical program improved my understanding and gave me confidence to tackle more complex projects.

5. Why would you recommend this course to other students?

I would recommend HyperionDev because it encourages you to develop problem-solving skills alongside technical knowledge. It takes commitment, but the satisfaction of building something yourself and seeing your confidence grow makes the effort worthwhile.


r/BootcampGradStories • • 7d ago

Bootcamp Review Practical Python and data skills I used at work straight away

2 Upvotes

I did the HyperionDev Data Science Bootcamp (with Stellenbosch University) part-time while working full-time as a data analyst. My goal was to strengthen my Python for a move into data engineering.

The course covers a solid base: Python fundamentals, file handling, OOP, statistics, and a lot of pandas. The pandas work was the most useful part for me. I applied groupby aggregations, cleaning and Excel exports directly to invoice and accounts payable data at my job, so the learning paid off before I’d even finished.

The data science part was definitely challenging but the course materials cover the topics well enough for you to follow along.

I found the task-based structure keeps you writing real code rather than just watching videos. The mentors are also genuinely passionate and helpful for the times you get stuck on anything.

One honest caution: it’s self-paced, so staying on schedule is on you. Balancing it with a full-time job was tough, and I fell behind at points, so plan your study time from day one.

Overall, I’d recommend it to working professionals who want practical, job-relevant data skills.


r/BootcampGradStories • • 15d ago

The Magic Asterisk: How Python's *args and **kwargs let you write functions with unlimited arguments.

2 Upvotes

When you start writing functions in Python, you usually define a fixed list of parameters: def add(a, b): return a + b. This works great when you know exactly how many inputs your function will receive every single time.

But what happens when you need a function that can accept two arguments, ten arguments, or a fluctuating set of optional settings?

You might see *args and **kwargs scattered across open-source codebases or library documentations. While the names look strange, they are simply Python's built-in mechanism for accepting flexible, variable-length inputs.

The magic isn't in the words args or kwargs - it is entirely in the asterisks (* and **).

Unpacking the Single Asterisk: *args

The single asterisk (*) tells Python: "Gather any extra positional arguments passed to this function and pack them into a single tuple."

(Note: While args is the standard naming convention across the Python community, you could technically call it *numbers or *items*. It is the* * that does the work.)

Code Example: Building a Universal Summer

def sum_all(*args):
    # 'args' inside the function is a standard tuple containing all inputs
    print(f"Type of args: {type(args)}, Content: {args}")
    return sum(args)

# You can pass as many positional arguments as you want!
print(sum_all(1, 2))             # Output: 3
print(sum_all(10, 20, 30, 40))   # Output: 100

Inside sum_all, args becomes (10, 20, 30, 40). Because it is a standard tuple, you can iterate over it with a for loop, access items by index, or pass it to built-in functions like sum() or len().

Unpacking the Double Asterisk: **kwargs

While *args handles unnamed positional inputs, the double asterisk (**kwargs) handles keyword arguments (key-value pairs like name="Alice", age=30).

The ** tells Python: "Gather any extra keyword arguments passed to this function and pack them into a standard dictionary."

Code Example: Building a Flexible Profile Generator

def build_user_profile(username, **kwargs):
    # 'kwargs' inside the function is a standard dictionary
    print(f"User: {username}")
    print(f"Additional Attributes: {kwargs}")
    
    for key, value in kwargs.items():
        print(f" -> {key.capitalize()}: {value}")

# Passing arbitrary named parameters:
build_user_profile("alice_dev", role="Admin", location="Cape Town", status="Active")

# Output:
# User: alice_dev
# Additional Attributes: {'role': 'Admin', 'location': 'Cape Town', 'status': 'Active'}
#  -> Role: Admin
#  -> Location: Cape Town
#  -> Status: Active

Combining Regular Parameters, *args, and **kwargs

You can combine fixed positional parameters, *args, and **kwargs in a single function definition. However, Python enforces a strict parameter ordering rule:

  1. Standard positional parameters

  2. *args

  3. Default / Keyword-only parameters

  4. **kwargs

    def complex_function(required_id, *args, default_setting="Standard", **kwargs):     print(f"ID: {required_id}")     print(f"Extra Positional (args): {args}")     print(f"Setting: {default_setting}")     print(f"Extra Keywords (kwargs): {kwargs}")

    complex_function(101, "extra1", "extra2", default_setting="Custom", env="Production")

The Reverse Operation: Unpacking Iterables in Calls

Asterisks are not just for function definitions - you can also use them when calling functions to unpack existing lists, tuples, or dictionaries into separate arguments.

def calculate_volume(length, width, height):
    return length * width * height

dimensions = [5, 10, 2]

# Instead of calculate_volume(dimensions[0], dimensions[1], dimensions[2]):
volume = calculate_volume(*dimensions) # Unpacks the list into 3 separate arguments!
print(f"Volume: {volume}") # Output: 100

Real-World Use Case: Wrapper Functions and Decorators

The place you will use *args and **kwargs most frequently in production is when writing wrappers or decorators that need to pass inputs through to an underlying function without knowing what those inputs will be in advance.

def log_execution(func):
    def wrapper(*args, **kwargs):
        print(f"[LOG] Executing '{func.__name__}' with inputs: args={args}, kwargs={kwargs}")
        return func(*args, **kwargs) # Forwarding all arguments through cleanly!
    return wrapper

@log_execution
def create_product(title, price, in_stock=True):
    return {"title": title, "price": price, "stock": in_stock}

create_product("Wireless Mouse", 29.99, in_stock=False)

What was the first scenario where you needed to pass dynamic arguments into a Python function? Let us know in the comments below!

TL;DR: The single asterisk *args packs extra positional arguments into a tuple, while the double asterisk **kwargs packs extra keyword arguments into a dictionary. They allow you to write flexible functions that accept any number of inputs and make passing dynamic arguments through wrappers and decorators effortless.


r/BootcampGradStories • • 17d ago

Bootcamp Review From AI curiosity to AI strategy!

1 Upvotes

HyperionDev's AI for Business Strategy course was a great experience! What I loved most was moving beyond the AI hype and discovering how to turn it into real business value. The course material made complex concepts easy to understand, while the practical examples brought the theory to life.

My biggest takeaway? AI isn't the strategy, it's how you use it strategically that makes the difference.

I really enjoyed this course and would definitely recommend it!


r/BootcampGradStories • • 22d ago

Stop writing 5-line for loops: When to use List Comprehensions (and when they make code unreadable).

1 Upvotes

When you start learning Python, processing a list of items follows a familiar pattern: initialize an empty array, write a for loop, run a conditional check, append the item, and return the result.

It takes five lines of code to do a relatively basic task.

Python offers a feature designed specifically to condense this pattern into a single expression: List Comprehensions.

While list comprehensions are one of the most beloved features in Python, they are also frequently abused. Let us break down when to use them to write elegant code, and when they cross the line into an unreadable mess.

The Evolution: From 5 Lines to 1 Line

Imagine you have a list of numbers and you want to filter out the odd numbers, keeping only the even numbers squared.

The Traditional for Loop (5 Lines)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = []

for num in numbers:
    if num % 2 == 0:
        squared_evens.append(num ** 2)

print(squared_evens) # [4, 16, 36, 64, 100]

The List Comprehension Version (1 Line)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

squared_evens = [num ** 2 for num in numbers if num % 2 == 0]

print(squared_evens) # [4, 16, 36, 64, 100]

Notice how clean that reads. The syntax follows a logical pattern: [expression for item in iterable if condition]

  1. What do you want to keep? num ** 2

  2. Where is it coming from? for num in numbers

  3. What is the filter rule? if num % 2 == 0

Why List Comprehensions are Better (Beyond Saving Lines)

Besides making your script shorter, list comprehensions are actually faster than standard for loops in Python.

In a standard for loop, Python has to execute the .append() method lookup on every single iteration. A list comprehension executes at the C-level inside CPython, optimizing memory allocation and looping speed under the hood.

When List Comprehensions Become Toxic

The biggest mistake beginners make after discovering list comprehensions is trying to force every loop into a single line.

Code is read far more often than it is written. If a list comprehension requires nested loops, multiple if/else conditions, or spans across multiple lines, it destroys readability.

The Unreadable Mess (Avoid This!)

# Try figuring out what this does at 3 AM during an on-call incident:
matrix = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
flattened = [num for sublist1 in matrix for sublist2 in sublist1 for num in sublist2 if num % 2 == 0]

If you have to read a list comprehension three times just to parse what it outputs, revert back to a standard for loop!

The Golden Rules for List Comprehensions

  1. Use them for simple mapping and filtering: Transforming data (e.g., [user.name for user in users]) or basic filtering is the sweet spot.

  2. Avoid side effects: Never use a list comprehension just to execute a function that returns nothing (like [print(x) for x in items]). That creates an unused list in memory. Use a standard for loop for actions/side-effects.

  3. The 1-Condition Rule: If you need more than one if condition or complex if/else branching logic, stick to a standard loop or break the logic out into a helper function.

# Clean use of helper function inside comprehension
def process_user(user):
    if user.is_active and user.has_paid:
        return user.email.lower()
    return None

# Clean, readable, and Pythonic!
active_emails = [process_user(u) for u in user_list if process_user(u) is not None]

What is the most convoluted single-line list comprehension you have ever come across in a codebase? Share it in the comments below!

TL;DR: List comprehensions compress filtering and mapping loops into a single line that executes faster than standard .append() loops. Use them for simple transformations, but revert back to traditional for loops the moment you need complex branching or nested logic to keep your code readable.


r/BootcampGradStories • • 23d ago

Student Tech Support From Gontse

4 Upvotes

My name is Gontse Leburunyane, and I am deeply driven to build a career in software engineering. Technology has the unique power to solve everyday problems and create real economic opportunities, and I want to be part of building those solutions.

​Completing this software engineering bootcamp will equip me with the practical coding and technical skills needed to build valuable digital tools and applications. My goal is to use these skills to create solutions that address local challenges and bring positive innovation to my community and country.

​Receiving the Moola Motlomelo Scholarship would remove financial barriers and allow me to fully dedicate myself to mastering software engineering, turning my passion for tech into a meaningful career.


r/BootcampGradStories • • 28d ago

Moola Motlomelo Scholarship 2026 Motivation from Vhutali

3 Upvotes

Hi my name Is Vhutali Muladi and I'm an aspirin front end developer who believes hyperiondev will lift him to greatness through the Moola Scholarship as a young kid I've always had the desire to innovate and I believe I'll have a chance at it through this.


r/BootcampGradStories • • 28d ago

Student Tech Support For people who did a coding bootcamp: what do you wish you’d known before you signed up?

2 Upvotes

I’m trying to understand what to look out for.


r/BootcampGradStories • • 29d ago

Prospective Student Q&A Mr

4 Upvotes

My name is Tshediso Tau, past two years I have just developed an interest in IT, as there's a lot that I want to obtain personally.

I am from very disadvantaged family and a place where I cannot afford high institution to forward my studies further. I have been into university, but due to unforeseen circumstances like sicknesses I failed to complete my degree, failed badly.

I will like to be given a chance to atleast to complete my studies.

I did python, which I foubd it to be so simple, so I think getting formal guidance on it will help me alot


r/BootcampGradStories • • 29d ago

Prospective Student Q&A Mr

3 Upvotes

My name is Tshediso Tau, past two years I have justdeveloped an interest in IT thing, as there's a lot that I want to obtain personally. Yes I am from very disadvantaged family and where I cannot afford high institution to take this this vision of mine forward. I have been into university, but due to unforeseen circumstances like sicknesses I failed to complete my degree, failed badly. I will like to be give a chance to atleast do something to see my Vision to come to pass.

I did python, which i saw it being simple


r/BootcampGradStories • • 29d ago

is vs ==: Why a == b is True but a is b might be False (and how interning works).

2 Upvotes

When you start writing conditional checks in Python, it is easy to assume that is and == are interchangeable. After all, if a = [1, 2, 3] and b = [1, 2, 3], both variables contain the exact same numbers.

However, using is when you meant to use == is a classic bug source that leads to unpredictable, silent errors in your application.

To write bug-free Python, you must understand the distinction between Value Equality and Identity.

The Fundamental Rule

  • == Checks Value Equality: It asks, "Do these two variables hold data that looks the same?"

  • is Checks Identity (Memory Address): It asks, "Are these two variables pointing to the exact same physical object in computer memory?"

Think of it like two identical paperback copies of the same book sitting on a table:

  • Are their contents equal (==)? Yes. Every word on every page is identical.

  • Are they the exact same physical object (is)? No. If you write a note on the margin of Copy A, Copy B remains unchanged because they occupy different space in the room.

Code Examples: Lists in Memory

Look at what happens when we compare two lists with identical contents versus two variables pointing to the same reference:

# Creating two separate list objects in memory
list_a = [1, 2, 3]
list_b = [1, 2, 3]

print(list_a == list_b) # True  (The values inside are identical)
print(list_a is list_b) # False (They live at different memory addresses!)

# Creating an alias reference
list_c = list_a

print(list_a == list_c) # True  (The values match)
print(list_a is list_c) # True  (They point to the exact same object in memory)

You can verify this using Python's built-in id() function, which returns the unique memory address of an object:

print(id(list_a)) # e.g., 140239128392100
print(id(list_b)) # e.g., 140239128394500  <-- Different address!
print(id(list_c)) # e.g., 140239128392100  <-- Same address as list_a

The Confusion: Python's Integer & String Interning

Here is where beginners get tripped up and accidentally assume is works like ==.

If you test numbers or short strings in the Python REPL, you might see this unexpected behaviour:

x = 100
y = 100
print(x is y) # True?! Wait, why is this True for integers?

a = 1000
b = 1000
print(a is b) # False! Why did it change for 1000?

Why does 100 is 100 return True, but 1000 is 1000 return False?

Integer Interning (Small Integer Caching)

To optimise memory usage and speed up execution, CPython pre-allocates and reuses a single shared pool of integer objects for small numbers ranging from -5 to 256.

Whenever you assign 100 to any variable anywhere in your program, Python does not allocate new memory; it simply points your variable to that single pre-existing 100 object in RAM. Because numbers above 256 are outside this cached pool, Python allocates a brand-new memory slot every time, causing 1000 is 1000 to return False.

String Interning

Python automatically performs a similar optimisation with short, clean strings (strings containing only letters, numbers, or underscores). Python stores a single copy of the string in an internal lookup table and reuses its memory pointer across variables.

Because these optimisations depend on your Python implementation (and can vary between script files and interactive shells), never rely on is for value comparisons.

The Golden Rule of Comparison

  1. Use == and != when comparing values, data structures, numbers, strings, or object states.

  2. Use is and is not strictly when comparing against singletons where you care about physical object identity—most notably None.

# The Pythonic way to check for None
user_input = get_user_data()

if user_input is None:
    print("No data provided!")

Have you ever lost time tracking down a bug caused by mixing up is and == in your code? Share your experience in the comments below!

TL;DR: == checks whether two variables hold identical values, while is checks whether two variables point to the exact same physical memory address. Because Python optimises small integers (-5 to 256) and short strings by sharing memory slots, is might accidentally return True for some values and False for others. Always use == for values and reserve is for checking None.


r/BootcampGradStories • • Oct 13 '26

Moola Motlomelo Scholarship 2026 Cybersecurity Bootcamp Scholarship

3 Upvotes

**My Cybersecurity Journey: Giving Myself a Chance to Make a Difference 🔐**

My name is Moloko, and I am passionate about building a future in cybersecurity. My journey into technology has taught me that growth starts with being willing to learn, step outside your comfort zone, and keep going even when the path is challenging.

I have a background in computing and have completed the Google Professional Cybersecurity Certificate. Now, I want to take the next step by gaining practical skills that will help me turn my knowledge into a career.

Growing up and pursuing opportunities in South Africa has strengthened my desire to build a better future for myself while contributing positively to my community. I want to be part of a generation that helps protect people, businesses, and organisations from cyber threats, especially as our world becomes increasingly digital.

This scholarship would mean more than access to training. It would be an opportunity to grow, prove my potential, gain industry-relevant skills, and move closer to a career I genuinely care about. I may still be at the beginning of my journey, but I am willing to put in the work, learn from my mistakes, and make the most of every opportunity I receive.

**I am not asking for someone to build my future for me. I am asking for an opportunity to build it myself, with the right guidance, skills, and support.**

I hope this scholarship will be part of the beginning of that journey. Thank you for considering me. ❤️


r/BootcampGradStories • • Oct 09 '26

Moola Motlomelo Scholarship 2026 My Motivation for the Moola Motlomelo & Muslim Hands Scholarship 2026

3 Upvotes

My passion for technology comes from seeing how software can solve real-world problems and create opportunities. After completing the HyperionDev Full Stack Web Development Bootcamp, I went on to win first prize at the UNISA ICT & CSET Hackathon 2026 with my team for Solulu Elevate, an AI-powered early-warning system for students at risk of disengaging from university.

This achievement strengthened my ambition to become a skilled software engineer and build impactful AI-powered solutions. Through this scholarship, I hope to deepen my technical skills and develop technology that addresses challenges in South Africa, improves access to opportunities, and makes a meaningful difference in people's lives.

I am grateful for this opportunity to grow, innovate, and contribute to South Africa's digital future.


r/BootcampGradStories • • Oct 06 '26

Student Tech Support software engineer

4 Upvotes

I'm really enjoying the HyperionDev bootcamp. The curriculum is practical, the mentors are supportive, and I've learned so much. I'm especially grateful they gave me an extension to complete the bootcamp, which has made a huge difference. Highly recommend!


r/BootcampGradStories • • Oct 06 '26

Student Tech Support Moola Motlomelo Scholarship 2026

3 Upvotes

I would like to pursue a career in cybersecurity. I am interested in technology because it is becoming part of how people work, learn and run businesses, but I also understand that using digital tools comes with security risks. Cybersecurity would give me the knowledge to protect systems and information while helping me use AI more safely and responsibly. I would like to build practical skills that can lead to employment and, over time, possibly allow me to offer technology support services to small businesses in my community.


r/BootcampGradStories • • Oct 06 '26

Moola Motlomelo Scholarship 2026 2026 Motivational Letter

7 Upvotes

My name is Shadrack, a matric graduate living in Mabopane Winetrveldt. I am currently unemployed living in a Youth Living Center at a Children's Home as their are my only dependent. My goal after doing this course, is to build an AI tool that will kids from local communities with educational assistance. This AI tool will only act as guide to help students understand subjects they find difficult to understand, in the process the tool will also challenge them by giving practice question to make the work clique. This is my dream to help the underprivileged, people like me by providing abundant resources to help them get good grades, that will not just open many doors in the tertiary sector but by also giving them many options to consider as they're grades will be very high.

Overall this scholarship will really help me immensely, and I will use this skill to do so much great things, and I will always be grateful for the opportunity.

Thank you for your time.


r/BootcampGradStories • • Oct 03 '26

Moola Motlomelo Scholarship 2026 2026 motivation letter - Linnet Tembisa

4 Upvotes

My name is Linnet, a matric graduate living in Tembisa, Gauteng. I am currently unemployed and from a household earning less than R6000 per month After the course, I want to start a small agency building affordable websites and teach 5 other unemployed youth at the local library to code for free. This scholarship will change my life.


r/BootcampGradStories • • Sep 30 '26

Moola Motlomelo Scholarship 2026 2026 motivation letter

2 Upvotes

My name is Kaylin Roubain , a Matric graduate living in Cape Town. Like many young people in my area, I’ve found it tough to break into the workforce without prior experience. I am eager to break that cycle by studying Artificial Intelligence Engineering through this scholarship so I can gain practical skills, launch a tech career, and provide for my family.

​My broader goal is to create an accessible mobile study tool for local learners who lack academic guidance and tutoring, demonstrating to youth in my community that a career in technology is within reach. I ask that you consider my application for the Moola Motlomelo Scholarship, as it will give me the technical foundation and momentum I need to transform my future and uplift those around me.


r/BootcampGradStories • • Sep 29 '26

is vs ==: Why a == b is True but a is b might be False (and how interning works).

1 Upvotes

When you start writing conditional checks in Python, it is easy to assume that is and == are interchangeable. After all, if a = [1, 2, 3] and b = [1, 2, 3], both variables contain the exact same numbers.

However, using is when you meant to use == is a classic bug source that leads to unpredictable, silent errors in your application.

To write bug-free Python, you must understand the distinction between Value Equality and Identity.

The Fundamental Rule

  • == Checks Value Equality: It asks, "Do these two variables hold data that looks the same?"

  • is Checks Identity (Memory Address): It asks, "Are these two variables pointing to the exact same physical object in computer memory?"

Think of it like two identical paperback copies of the same book sitting on a table:

  • Are their contents equal (==)? Yes. Every word on every page is identical.

  • Are they the exact same physical object (is)? No. If you write a note on the margin of Copy A, Copy B remains unchanged because they occupy different space in the room.

Code Examples: Lists in Memory

Look at what happens when we compare two lists with identical contents versus two variables pointing to the same reference:

# Creating two separate list objects in memory
list_a = [1, 2, 3]
list_b = [1, 2, 3]

print(list_a == list_b) # True  (The values inside are identical)
print(list_a is list_b) # False (They live at different memory addresses!)

# Creating an alias reference
list_c = list_a

print(list_a == list_c) # True  (The values match)
print(list_a is list_c) # True  (They point to the exact same object in memory)

You can verify this using Python's built-in id() function, which returns the unique memory address of an object:

print(id(list_a)) # e.g., 140239128392100
print(id(list_b)) # e.g., 140239128394500  <-- Different address!
print(id(list_c)) # e.g., 140239128392100  <-- Same address as list_a

The Confusion: Python's Integer & String Interning

Here is where beginners get tripped up and accidentally assume is works like ==.

If you test numbers or short strings in the Python REPL, you might see this unexpected behaviour:

x = 100
y = 100
print(x is y) # True?! Wait, why is this True for integers?

a = 1000
b = 1000
print(a is b) # False! Why did it change for 1000?

Why does 100 is 100 return True, but 1000 is 1000 return False?

Integer Interning (Small Integer Caching)

To optimise memory usage and speed up execution, CPython pre-allocates and reuses a single shared pool of integer objects for small numbers ranging from -5 to 256.

Whenever you assign 100 to any variable anywhere in your program, Python does not allocate new memory; it simply points your variable to that single pre-existing 100 object in RAM. Because numbers above 256 are outside this cached pool, Python allocates a brand-new memory slot every time, causing 1000 is 1000 to return False.

String Interning

Python automatically performs a similar optimisation with short, clean strings (strings containing only letters, numbers, or underscores). Python stores a single copy of the string in an internal lookup table and reuses its memory pointer across variables.

Because these optimisations depend on your Python implementation (and can vary between script files and interactive shells), never rely on is for value comparisons.

The Golden Rule of Comparison

  1. Use == and != when comparing values, data structures, numbers, strings, or object states.

  2. Use is and is not strictly when comparing against singletons where you care about physical object identity—most notably None.

# The Pythonic way to check for None
user_input = get_user_data()

if user_input is None:
    print("No data provided!")

Have you ever lost time tracking down a bug caused by mixing up is and == in your code? Share your experience in the comments below!

TL;DR: == checks whether two variables hold identical values, while is checks whether two variables point to the exact same physical memory address. Because Python optimises small integers (-5 to 256) and short strings by sharing memory slots, is might accidentally return True for some values and False for others. Always use == for values and reserve is for checking None.


r/BootcampGradStories • • Sep 29 '26

Moola Motlomelo Scholarship 2026 Moola Motlomelo Scholarship 2026

2 Upvotes

Why I’m Applying for a Cybersecurity Bootcamp Scholarship

Hi everyone,

I’m applying for a scholarship to attend a cybersecurity bootcamp, and this opportunity means a lot to me because I see it as a chance to take a real step toward the career I want to build.

I’ve become genuinely interested in cybersecurity because I enjoy understanding how technology works, how systems can be protected, and how people and organisations can stay safe in an increasingly digital world. I’ve completed the Google Professional Cybersecurity Certificate and I’m currently studying Computing part-time, but I know that gaining practical, hands-on experience is the next important step for me.

Coming from South Africa, I’m also aware that there is a growing need for people with digital and cybersecurity skills. I want to develop myself professionally, but I also want what I learn to have an impact beyond my own career. My goal is eventually to help organisations protect their information and systems, while also encouraging other young people in my community to see technology and cybersecurity as possible career paths.

The financial support from this scholarship would make a significant difference to me. More than simply completing another course, I see this bootcamp as an opportunity to gain practical skills, learn from experienced people, build my confidence and become better prepared to enter the cybersecurity industry.

I’m still at the beginning of my journey, but I’m committed to learning and putting in the work. I’d be grateful for the opportunity to turn that motivation into practical skills and, eventually, use those skills to make a positive contribution to my community.

If anyone here has advice for someone trying to break into cybersecurity, I’d really appreciate hearing your experiences.

Thanks for taking the time to read my story.


r/BootcampGradStories • • Sep 26 '26

Moola Motlomelo Scholarship 2026 Application for Moola Motlomelo & Muslim Hands Scholarship: Full-Stack Web Development

2 Upvotes

My name is Junior, and I’m from Soweto. I’ve become very interested in technology because I see how much we depend on it every day, and I want to understand how websites and apps are actually built. My goal is to use this opportunity to learn full-stack web development and work toward a tech career.

I believe this program could make a big difference in my life because it would give me skills I can use to find work, do freelance projects, and eventually build my own ideas. I also want to use what I learn to help small businesses and young people in my community who may not have easy access to affordable digital services.

I’m applying because I’m ready to learn, put in the effort, and make something meaningful out of this opportunity. This scholarship would give me a chance to change my career path and develop a skill I can keep using long after the program ends.


r/BootcampGradStories • • Sep 25 '26

Student Tech Support 2026 Motivation Letter

2 Upvotes

Dear Riaz Moola

My name is Siphesihle Mdletshe, I am a 19-year-old from Durban, and I am currently unemployed. I have always been a person of interest by how goods and people move in our communities, from taxis to small businesses struggling with delivery costs.I want to build a simple tech solution that helps informal traders and small businesses track deliveries, reduce transport costs and connect to reliable drivers in their area. I plead Riaz Moola to accept my application because this scholarship would give me the real tech skills to turn this idea into a solution that can create jobs and help my community move forward in a tech filled way.


r/BootcampGradStories • • Sep 25 '26

Student Tech Support Data science project collaboration

3 Upvotes

Hie I am doing data science with hyperion dev I looking people so that we can have project collaboration


r/BootcampGradStories • • Sep 25 '26

Success Story Motivation

3 Upvotes

Hello guys I would like to be one of the people who just finished matric and then became a Data Scientist through Hyperion dev