Python & Data Science

Python Syntax Quick Reference Lists Conditionals L

You write a neat little function to collect items. It has a default empty list. You call it once. Fine. You call it again—and the list from the first call is still there. Items are piling up like ghosts you never invited. You stare at the screen and ask the question every Python beginner asks: Why does Python do this?

That moment of confusion isn’t a sign you’re bad at programming. It’s a sign you’ve bumped into one of Python’s most famous traps—a trap that’s completely predictable once you understand the mental model underneath it. This article is your map of the syntax you’ll write every day, with explicit, plain-English warnings about the parts that bite. Think of it as a quick-reference you can bookmark and return to, not a tutorial that holds your hand through installing Python. We’ll cover the core syntax first—lists, conditionals, loops—and then spend most of our time on the idioms that trip up beginners. By the end, you’ll understand the why behind the gotchas, not just the what.

Let’s start with the trap that opens our story.

# The trap: a mutable default argument
def add_item(item, my_list=[]):
    my_list.append(item)
    return my_list

# First call — looks fine
print(add_item("apple"))   # ['apple']

# Second call — wait, why is 'apple' still there?
print(add_item("banana"))  # ['apple', 'banana']

# The fix: default to None and create the list inside the function
def add_item_fixed(item, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(item)
    return my_list

print(add_item_fixed("apple"))   # ['apple']
print(add_item_fixed("banana"))  # ['banana'] — fresh list each time

That None guard is the fix you’ll use for the rest of your Python life. But to really understand why it works, we need to build a mental model of how Python treats names and objects. We’ll get there. First, let’s lay down the syntax you’ll use every single day.

Core Syntax Quick-Reference: Lists, Conditionals, and Loops

This section is your cheat sheet. Each row shows the idiomatic way to write something in Python, the common beginner alternative, and a one-line explanation. You can scan it now and come back when you need a refresher.

List Comprehensions

When you’re building a new list by transforming each item in an existing sequence, a list comprehension is the Pythonic way. It’s shorter, faster to read, and avoids the multi-line for-loop-with-.append() pattern.

# Idiomatic: list comprehension
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Beginner alternative: for loop with .append()
squares_alt = []
for x in range(10):
    squares_alt.append(x**2)
print(squares_alt)  # same result, more lines

Here’s the catch with tuple expressions inside comprehensions: if you want each element to be a tuple, you must wrap it in parentheses. Without them, Python thinks you’re trying to unpack something and raises a SyntaxError.

# Correct: parenthesized tuple in a comprehension
tuples = [(x, x**2) for x in range(6)]
print(tuples)  # [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

# Wrong: missing parentheses — this is a SyntaxError
# tuples_bad = [x, x**2 for x in range(6)]  # uncomment to see the error

Slicing and del

Slicing lets you grab a chunk of a list. The del statement lets you delete a chunk—or the whole list contents—in place.

a = [10, 20, 30, 40, 50]

# Delete a slice
del a[1:3]
print(a)  # [10, 40, 50] — indices 1 and 2 are gone

# Clear the entire list in place
del a[:]
print(a)  # [] — the list object still exists, but it's empty

Looping Idioms: enumerate() and zip()

If you’re writing for i in range(len(x)), stop. Python gives you enumerate() for when you need the index and the value, and zip() for when you need to pair up multiple sequences. These are clearer and less error-prone.

fruits = ["apple", "banana", "cherry"]

# Idiomatic: enumerate() for index + value
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

# Beginner alternative: range(len())
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")  # works, but harder to read
names = ["Alice", "Bob", "Carol"]
scores = [85, 92, 78]

# Idiomatic: zip() for parallel iteration
for name, score in zip(names, scores):
    print(f"{name} scored {score}")
# Alice scored 85
# Bob scored 92
# Carol scored 78

sorted() vs .sort()

This one trips up beginners constantly. sorted() returns a new sorted list and leaves the original untouched. .sort() sorts the list in place and returns None. If you write b = a.sort(), b will be None.

a = [3, 1, 2]

# sorted() returns a new list
b = sorted(a)
print(b)  # [1, 2, 3]
print(a)  # [3, 1, 2] — original unchanged

# .sort() sorts in place and returns None
result = a.sort()
print(result)  # None
print(a)        # [1, 2, 3] — original is now sorted

elif, Not else if

Python’s chained-conditional keyword is elif. Writing else if will give you a syntax error.

x = 42

if x < 0:
    print("negative")
elif x == 0:
    print("zero")
else:
    print("positive")  # this runs

range() Is Exclusive and Iterable

range(stop) goes up to, but does not include, stop. And in Python 3, range() returns an iterable, not a list. If you need a list, wrap it: list(range(5)).

# range(stop) is exclusive of stop
print(list(range(5)))  # [0, 1, 2, 3, 4] — 5 is not included

# range() is an iterable, not a list
r = range(3)
print(r)        # range(0, 3)
print(list(r))  # [0, 1, 2]

Argument Unpacking: *args and **kwargs

When you have a list or a dict and you want to pass its contents as separate arguments to a function, use * for sequences and ** for mappings.

def greet(greeting, name):
    return f"{greeting}, {name}!"

# Unpack a list into positional arguments
args = ["Hello", "Alice"]
print(greet(*args))  # Hello, Alice!

# Unpack a dict into keyword arguments
kwargs = {"greeting": "Hi", "name": "Bob"}
print(greet(**kwargs))  # Hi, Bob!

That’s the core syntax you’ll write every day. Now let’s tackle the part that actually keeps you up at night: the idioms that look like bugs but aren’t.

The Idioms That Trip Up Beginners (and Why They’re Not Bugs)

All of the gotchas we’re about to cover stem from one core idea: Python variables are names that refer to objects, not boxes that contain them. In many other languages, a variable is a box—you put a value in it, and if you assign that variable to another, you get a copy of the value. Python doesn’t work that way. A Python variable is more like a sticky note with a name written on it, stuck to an object. Assignment sticks a new sticky note on an object; it doesn’t create a new object. Once you internalize this, mutable defaults, aliasing, and the is vs == distinction all become obvious. Truthiness is a separate but complementary feature—Python’s way of letting you write concise, readable conditionals.

Let’s walk through each gotcha. For each one, we’ll show the surprising behavior, explain what’s actually happening in plain English, give the fix, and connect it back to the mental model.

Gotcha 1: Mutable Default Arguments

This is the trap from our introduction, and it’s the most famous Python gotcha for a reason. Let’s look at it again, more carefully.

def add_item(item, my_list=[]):
    my_list.append(item)
    return my_list

print(add_item("apple"))   # ['apple']
print(add_item("banana"))  # ['apple', 'banana'] — the list grew!

What’s actually happening here? In Python, default argument values are evaluated exactly once: when the function is defined, not when it’s called. That empty list [] is created at definition time, and every call that doesn’t provide a second argument uses that same list object. It’s a single list, shared across all calls. The first call appends "apple" to it. The second call appends "banana" to the same list. You’re mutating a shared object.

This is the same underlying issue as assignment and aliasing—multiple names (the my_list parameter across different calls) refer to the same object. The fix is to default to None and create the mutable object inside the function body.

def add_item_fixed(item, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(item)
    return my_list

print(add_item_fixed("apple"))   # ['apple']
print(add_item_fixed("banana"))  # ['banana'] — fresh list each call

What this actually means: Never use a mutable object (list, dict, set) as a default argument unless you want it to be shared across calls. Default to None and create the mutable object inside the function. This is the hardest part of the mutable-default trap to remember, because it looks like the default should be re-created each call—but it isn’t.

Gotcha 2: Assignment Doesn’t Copy (Aliasing)

This is the same mental model, applied to regular assignment. When you write b = a where a is a list, you are not creating a new list. You are creating a second name for the same list object.

a = [1, 2, 3]
b = a           # b is now another name for the same list
b.append(4)
print(a)        # [1, 2, 3, 4] — a changed too!
print(b)        # [1, 2, 3, 4]

Think of it this way: you have one shopping list stuck to the fridge. a is a sticky note that says “the shopping list.” b = a writes a second sticky note that also says “the shopping list.” If someone adds “eggs” to the shopping list, both sticky notes now point to a list that includes “eggs.” You didn’t copy the list; you copied the reference to it.

If you actually want a copy, you need to be explicit. For a flat list, a shallow copy is enough—it creates a new outer container, but the inner objects are still shared. For nested structures, you need a deep copy, which recursively copies everything.

import copy

# Shallow copy: new outer list, same inner objects
a = [[1, 2], [3, 4]]
b = list(a)      # or a[:] or copy.copy(a)
b[0].append(99)
print(a)         # [[1, 2, 99], [3, 4]] — inner list is shared!
print(b)         # [[1, 2, 99], [3, 4]]

# Deep copy: everything is copied recursively
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
b[0].append(99)
print(a)         # [[1, 2], [3, 4]] — original untouched
print(b)         # [[1, 2, 99], [3, 4]]

What this actually means: Assignment never copies. If you mutate an object through one name, every other name for that object sees the change. Use list(a), a[:], or copy.copy(a) for a shallow copy, and copy.deepcopy(a) when you have nested mutable objects. This is the same “names are references” model that explains mutable defaults.

Gotcha 3: Truthiness — When if x: Isn’t What You Meant

Python lets you write if x: as a shorthand for “if x has a value that isn’t empty or zero.” That’s usually convenient, but it bites when zero or an empty container is a valid, meaningful value in your program.

# The trap: zero is falsy, so this loop skips it
count = 0
if count:
    print("Count is non-zero")
else:
    print("Count is zero or empty")  # this runs — but what if zero is a valid count?

Python treats the following values as falsy: None, False, zero of any numeric type (0, 0.0, 0j), empty sequences and collections ('', (), [], {}, set(), range(0)). Everything else is truthy. This is a feature: it lets you write if my_list: to check if the list is non-empty, which reads naturally. But when zero or an empty container is a valid value, you need to be explicit.

# The fix: be explicit about what you're checking
count = 0

if count is not None:
    print("Count is not None")  # this runs — zero is not None

if count != 0:
    print("Count is non-zero")
else:
    print("Count is zero")      # this runs — explicit and correct

What this actually means: if x: checks truthiness, not whether x is None. If zero, an empty string, or an empty list is a valid value in your context, use if x is not None: or an explicit comparison. Otherwise, enjoy the concise, readable conditionals Python gives you.

Gotcha 4: is vs == — Identity Is Not Equality

This is the gotcha that separates “I write Python” from “I understand Python.” The is operator checks object identity: are these two names pointing to the exact same object in memory? The == operator checks value equality: do these two objects have the same value?

# Two lists with the same value are equal, but not identical
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True — same value
print(a is b)  # False — different objects in memory

# But if they're the same object, both are True
a = [1, 2, 3]
b = a
print(a == b)  # True
print(a is b)  # True — same object

Now here’s the interesting part. CPython, the default Python implementation, caches small integers for performance. So x is 7 might accidentally work—but it’s wrong either way, and newer Python versions will warn you about it.

# The integer-caching quirk
x = 7
y = 7
print(x is y)   # True — CPython caches small integers, so they're the same object

x = 700
y = 700
print(x is y)   # False — larger integers are not cached, so they're different objects

What this actually means: Use is only for singletons like None, True, and False. Use == for everything else. If you write if x is 7:, you’re relying on an implementation detail that can change. Don’t do it.

Gotcha 5: The for...else Clause (Yes, It Exists)

This syntax looks like a typo. The else clause on a for loop runs only if the loop completed without hitting a break. It does not run if the loop was broken out of. And crucially, the else belongs to the for loop, not to the if statement inside it—a routinely misread piece of syntax.

# Search for a prime factor using for...else
def has_prime_factor(x):
    for n in range(2, x):
        if x % n == 0:
            print(f"{x} has a factor: {n}")
            break
    else:
        # This runs only if the loop completed without a break
        print(f"{x} is prime!")

has_prime_factor(11)  # 11 is prime!
has_prime_factor(12)  # 12 has a factor: 2

Think of it this way: the else block is the “no-break” block. It’s useful for search patterns: “if you found it, break; else, handle the not-found case.” Without for...else, you’d need a flag variable to track whether you broke out of the loop.

What this actually means: The else on a for loop is optional and counterintuitive. If it confuses you, skip it—a flag variable is more verbose but clearer to many readers. But if you see it in someone else’s code, now you know it means “ran to completion without breaking.”

Putting It All Together: The Mental Model That Explains Everything

All five gotchas become predictable when you internalize one idea: Python variables are names that refer to objects, not boxes that contain them. Assignment creates a new name, not a new object. Default arguments are evaluated once, at definition time. is checks if two names point to the same object. Once you have that model, the gotchas aren’t gotchas—they’re just consequences.

Let’s see the model in one annotated block.

# The mental model in one place

# 1. Assignment creates a new name, not a new object
a = [1, 2, 3]
b = a               # b is a new name for the SAME list object
b.append(4)
print(a)            # [1, 2, 3, 4] — a sees the mutation

# 2. Default arguments are evaluated ONCE at definition time
#    (This is why the mutable-default trap exists)

# 3. is checks object identity — are these the SAME object?
print(a is b)       # True — a and b name the same list

c = [1, 2, 3, 4]
print(a == c)       # True — same value
print(a is c)       # False — different objects

# 4. Truthiness is a separate, complementary feature
if a:
    print("a is truthy")  # this runs — non-empty lists are truthy

Here’s your gotcha-recap in one short list:

  1. Mutable default arguments: Default to None, create the mutable object inside the function.
  2. Assignment doesn’t copy: Use list(a), a[:], or copy module methods when you need a copy.
  3. Truthiness: Be explicit (is not None or != 0) when zero/empty is a valid value.
  4. is vs ==: Use is for singletons (None, True, False); use == for value equality.
  5. for...else: The else runs only if no break occurred. Optional, but good to recognize.

You don’t need to memorize every gotcha. You need to understand the model, and the gotchas become obvious.

Check Your Understanding

Test yourself against these prompts. They move from simple recall to creative application—the full Bloom’s taxonomy ladder.

Remember: List the five values Python treats as falsy that most often trip up beginners.

Understand: Explain in plain English why def f(x=[]): is a trap. What is Python doing at function definition time?

Apply: Fix this broken function:

def add_to_cart(item, cart=[]):
    cart.append(item)
    return cart

Analyze: Here are two code snippets. Which one has an aliasing bug, and why?

# Snippet A
a = [1, 2, 3]
b = a
b.append(4)
print(a)

# Snippet B
a = [1, 2, 3]
b = list(a)
b.append(4)
print(a)

Evaluate: A colleague writes if x is 7: in a code review. Explain why it’s wrong and what they should use instead.

Create: Write a for...else loop that searches a list of numbers for a value greater than 100. If it finds one, print “Found” and the value. If it doesn’t, print “Not found.”

Apply What You Learned

Here’s a script that works but breaks several of the rules we’ve covered. It uses a mutable default argument, a for i in range(len(x)) loop, and manual index-based pairing of two lists. Your task: refactor it into idiomatic Python.

Before script:

def merge_scores(names, scores, result=[]):
    for i in range(len(names)):
        result.append((names[i], scores[i]))
    return result

names = ["Alice", "Bob", "Carol"]
scores = [85, 92, 78]
print(merge_scores(names, scores))
print(merge_scores(names, scores))  # bug: result accumulates across calls

Deliverable: A cleaned-up version of the script that:

  • Uses a None-guarded default instead of a mutable default.
  • Replaces range(len()) with enumerate() or zip().
  • Produces the same correct output without the accumulation bug.

Self-check rubric:

  • Does the script produce the same output on the first call?
  • Does the second call produce the same output as the first (no accumulation)?
  • Is the code shorter and more readable than the original?
  • Are enumerate() or zip() used instead of range(len())?
  • Python Engineering Under review

    Python String Formatting Reference Format And F St

    print("Hello, %s! Your number is %d." % (name, value)) print("Hello, {}! Your number is {}.".format(name, value)) print(f"Hello, {name}! Your number is {value}.")

  • Python Engineering Under review

    Sending Automated Emails And Reports From A Python

    You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file.

  • Python Engineering Under review

    Reinforcement Learning Algorithms Reference Which

    Before we name a single algorithm, we need to name the axes that separate them. Otherwise, you’re memorizing names without knowing why they differ—like learning the names of every screwdriver without knowing whether your screw is flathead or Phillips. Let’s fix that.

  • Python Engineering Under review

    Reading And Writing Excel Files At Scale With Open

    Let’s make the problem crystal clear. When you call `pd.read_excel()` or open an `openpyxl.Workbook` in default mode, Python creates a full object for every cell.

Looking for something else?

Search every article by title, summary or topic.