How to Fix TypeError: ‘int’ object is not iterable in Python

3D vector banner for solving integer not iterable errors in Python loops.

In Python, an iterable is any object capable of yielding its members one at a time—such as a list, tuple, dict, set, str, or range object. A single integer—whether 5, 0, -1, or a 100-digit number like 10**100—is a scalar value, not a collection. Whenever you try to loop over an integer (for i in 5:), delegate to an integer in a generator (yield from 42), pass a single integer into a function that expects a collection (sum(10, 20), list(42), map(str, 42), enumerate(5)), or call my_list.extend(3), Python halts with TypeError: 'int' object is not iterable.

Reading the 'int' object is not iterable Traceback

Read the traceback from the bottom up. Python raises this error the moment it calls iter(obj) on an integer and discovers that the int class does not implement the iterator protocol:

Traceback (most recent call last):
  File "/var/www/app/main.py", line 2, in <module>
    for i in count:
TypeError: 'int' object is not iterable
  • Python 3.11+ Carets: Starting in Python 3.11+ (not run by me; noted from documentation), the traceback points ^^^^^ carets directly at the integer expression or function call that triggered the failed iteration.

Tested Environment: Python 3.10.16, NumPy 1.26.3 & Pandas 2.0.0 (Linux) | Python 3.11+ carets, Django, and linter/type-checker CLI outputs not run by me; noted from documentation.

Part of: The Ultimate Python Debugging Guide

⚡ The Quick Fix: Use range(), .append(), or Wrap the Integer in [...]

Choose the fix that matches what you were trying to do with the integer:

1. Repeat a Loop N Times: Wrap the Integer in range() If count = 5 and you want a for loop to run 5 times (or iterate over list indices using len(items)), wrap the integer in range():

count = 5

# Fails: 'count' is an int (5), not a sequence
# for i in count:

# Fix: range(5) produces an iterable yielding 0, 1, 2, 3, 4
for i in range(count):
    print(i)

2. Add a Single Integer to a List: Use .append(x) Instead of .extend(x) or += x Both my_list.extend() and my_list += ... expect an iterable and loop over it internally. To add one integer to the end of a list, use .append() (or wrap the integer in brackets [30]):

scores = [10, 20]

# Fails: .extend(30) and scores += 30 try to iterate over 30
# scores.extend(30)

# Fix: Use .append(30) for a single item (or scores += [30])
scores.append(30)
print(scores)  # Prints: [10, 20, 30]

3. Functions Returning 0 or -1 on Error: Return [] or Raise an Error When a helper function returns a list of records on success, never return 0 or -1 when no records are found:

# Optional data: Always return an empty list [] so callers can safely loop over it
def get_user_ids_optional(users):
    if not users:
        return []
    return [u["id"] for u in users]

# Required data: Validate and raise a meaningful error instead of returning an int error code
def get_user_ids_strict(users):
    if not users:
        raise ValueError("Expected at least one user record, got an empty collection.")
    return [u["id"] for u in users]

The 10-Second Diagnostic: What Your TypeError: 'int' object is not iterable Looks Like

Find the pattern that matches your crashing line to grab the exact fix in under 15 seconds:

What the Code Looks LikeRoot CauseThe Exact Fix
for i in len(items): (or for i in 5:)len() returns an int, not a sequence.Wrap in range(): for i in range(len(items)):
sum(10, 20)sum() expects an iterable first argument.Use 10 + 20 or sum([10, 20])
items.extend(42) (or items += 42)extend() and += iterate over their argument.Use items.append(42) or items += [42]
enumerate(len(items)) (or zip(a, 10) / map(str, 42))enumerate(), zip(), and map() require iterables.Pass the collection: enumerate(items)
list(42) / tuple(42)list() converts iterables, not scalars.Use brackets: [42] or (42,)
yield from 42 (in a generator)yield from delegates to a sub-iterable.Use yield 42 for a single value.
for digit in 12345:Integers cannot be iterated digit-by-digit.Convert to str: [int(d) for d in str(12345)]
for x in (42):Parentheses without a comma evaluate to int.Add a trailing comma: for x in (42,):
for x in df[“col”].item(): (or df[“price”].apply(sum)).item() and Series.apply() yield scalar int values.Iterate df[“col”] or call df[“price”].sum()

Can You Fix This TypeError?

count = 5
for i in count:
    print(i)

Choose the best fix:

Table of contents

Debugging & Verifying Iterable Objects in Python

How Python Determines Whether an Object Is Iterable

Whenever you run a for loop, unpack a sequence, or call list(obj), CPython internally invokes the built-in iter(obj) function (PyObject_GetIter at the C level):

  1. What iter(obj) Does: iter(obj) asks the object for an iterator capable of producing values one at a time via next(). It checks two mechanisms in strict order.
  2. What __iter__() Does (Primary Protocol): Python first checks whether the object’s class defines an __iter__(self) method. Standard collections (list, tuple, dict, set, str, range) implement __iter__() and return a dedicated iterator object that implements __next__().
  3. How __getitem__() Provides Legacy Iteration Support: If an object does not define __iter__(), iter(obj) falls back to Python’s legacy sequence protocol: it checks whether the class defines __getitem__(self, index). If present, Python constructs a sequence iterator that repeatedly calls obj[0], obj[1], obj[2]… until IndexError is raised to stop the loop.
  4. Why Integers Fail (Including 0, -1, and 10**100): Built-in int objects represent scalar numbers and implement neither __iter__() nor __getitem__(). Because both checks fail, iter(x) raises the exact same TypeError: 'int' object is not iterable whether the integer is positive (5), zero (0), negative (-1), or an arbitrary-precision huge integer (10**100).
  5. Why Checking isinstance(obj, Iterable) Isn’t a Universal Test: Many developers test iterability using from collections.abc import Iterable; isinstance(obj, Iterable). However, Iterable only checks whether the class defines __iter__—it completely misses legacy objects that iterate via __getitem__(). Calling iter(obj) inside a try / except TypeError block is the only 100% definitive runtime test in Python:
from collections.abc import Iterable

class LegacySequence:
    def __getitem__(self, index):
        if index >= 3:
            raise IndexError(index)
        return index * 10

seq = LegacySequence()
print("isinstance(seq, Iterable):", isinstance(seq, Iterable))
print("list(iter(seq)):          ", list(iter(seq)))

Verified Output (Python 3.10.16):

isinstance(seq, Iterable): False
list(iter(seq)):           [0, 10, 20]

Step-by-Step Debugging Workflow

When TypeError: 'int' object is not iterable appears in a complex pipeline, follow this exact 7-step sequence to isolate and fix the bug at its source:

  1. Identify the exact failing line from the traceback: Look at the bottom frame of the traceback to see which for loop, comprehension, unpacking assignment, or function call (sum(), list(), extend(), zip()) triggered the crash.
  2. Identify the variable being passed into the iteration context: Pinpoint the exact variable or function call return value being iterated (for example, user_ids in for uid in user_ids:).
  3. Print type(variable).__name__: Confirm right above the failing line that the variable’s runtime type is 'int' (or 'int64').
  4. Print repr(variable): Inspect the exact integer value (0, -1, 404, or 5). The number itself is a major clue: 0 or -1 usually indicates a C-style error return or database row count, 200/404 indicates an HTTP status code, and a small positive integer often comes from len().
  5. Test it using iter(variable): In an interactive debugger (pdb or breakpoint()), test iter(variable) to confirm which sub-expression in a chained line is non-iterable.
  6. Trace where the unexpected integer originated: Follow the variable backward to its assignment—check whether a variable name was shadowed (items = len(items)), a tuple comma was omitted ((42)), or a helper function returned an integer status code instead of a list.
  7. Fix the original data source rather than merely suppressing the exception: Never wrap a broken loop in try ... except TypeError: pass. Fix the producer so it consistently returns an iterable (such as []) or raises a descriptive exception when data is invalid.
# Quick 3-line diagnostic to drop right above the crashing line:
target = 42
print("Type:", type(target).__name__, "| Value:", repr(target))
try:
    iter(target)
except TypeError as err:
    print("iter() check failed:", err)

Common Causes of TypeError: 'int' object is not iterable

Here are the nine most frequent ways a single integer ends up in an iteration context.

1. Looping Over len(items), 0, or Negative Integers Instead of range()

Beginners frequently write for i in len(items): when they want to loop over the indices of a list, or for i in count: when they want a loop to repeat count times. Because len(items) and count are int objects, Python cannot iterate over them directly.

  • The Trigger (Verified 3.10.16):
items = ["apple", "banana", "cherry"]
for i in len(items):
    print(items[i])
# TypeError: 'int' object is not iterable

The Fix: Iterate directly over the list (for item in items:), use enumerate(items) if you need both the index and the item, or wrap len(items) in range():

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

# Best Pythonic approach: loop over items directly (or with enumerate)
for idx, item in enumerate(items):
    print(idx, item)

# Index-only approach: wrap len() in range()
for i in range(len(items)):
    print(items[i])
  • 💡 Zero & Negative Integers (for i in -5 vs. range(-5)): Iterating directly over 0 or -5 (for i in 0: or for i in -5:) raises TypeError: 'int' object is not iterable. By contrast, range(0) and range(-5) are completely legal in Python—because the stop value is less than or equal to the default start (0), range(-5) returns an empty range object (list(range(-5)) is []), allowing your for loop to safely execute zero times without crashing. ⚠️ Watch Out for the range(float) Sibling Error: Standard division / in Python 3 always returns a float (10 / 2 evaluates to 5.0). Passing a float or division result into range(3.5) or range(len(items) / 2) raises TypeError: 'float' object cannot be interpreted as an integer. Always use floor division // (range(len(items) // 2)) for whole steps, or numpy.arange(0, 3.5, 0.5) for decimal steps.

2. Calling sum(10, 20) Instead of sum([10, 20]) or 10 + 20

Unlike max(10, 20) and min(10, 20)—which accept either two positional numbers or a single iterable—built-in sum(iterable, start=0) always requires an iterable as its first argument. Writing sum(10, 20) tells Python to iterate over 10 (starting from 20), which crashes immediately! Similarly, passing a single integer to max(42), min(42), sorted(42), any(0), or all(1) raises this exact TypeError.

  • The Trigger (Verified 3.10.16):
total = sum(10, 20)
# TypeError: 'int' object is not iterable
  • The Fix: Add two numbers directly with 10 + 20, or wrap the numbers in a list or tuple inside sum([10, 20]):
total = sum([10, 20])
print(total)  # Prints: 30
  • How to tell it’s this one: The crash happens on a line calling sum(), max(), min(), sorted(), any(), or all().

3. Passing Scalar Integers to map(), filter(), zip(), or enumerate() (And How itertools.repeat() Saves Memory)

Built-in iterator constructors—map(fn, iterable), filter(fn, iterable), zip(*iterables), and enumerate(iterable)—all require iterable collections. Even though these four functions return lazy iterators, CPython validates that their arguments are iterable immediately when you call them, before your loop even begins:

  1. The map() and filter() Trap (map(str, 42)): Passing a single integer 42 instead of [42] as the second argument to map() or filter() crashes immediately.
  2. The enumerate(len(items)) Mix-Up: Writing for i, x in enumerate(len(items)): instead of enumerate(items) passes the integer length to enumerate().
  3. The zip() Scalar Mismatch (zip(names, 100)): Passing a list as the first argument to zip() and a constant integer as the second argument crashes as soon as zip() inspects the integer.
  • The Trigger (Verified 3.10.16):
# All three calls fail immediately with TypeError: 'int' object is not iterable:
# m = map(str, 42)
# e = enumerate(5)
z = zip(["alice", "bob"], 100)

The Fix & Using itertools.repeat() ($O(1)$ Memory): Pass the actual collection (items) to enumerate(), map(), and filter().

💡 Performance & Memory Note: When pairing a collection of $n$ items with a constant integer in zip() or map(), use itertools.repeat(100) instead of [100] * len(names). While [100] * n allocates an $O(n)$ list in RAM, itertools.repeat(100) uses $O(1)$ constant memory—yielding the same integer reference on demand whether your dataset has 10 rows or 10 million rows:

import itertools

names = ["alice", "bob", "charlie"]

# O(1) memory pairing with constant integer 100:
paired = list(zip(names, itertools.repeat(100)))
print(paired)   # [('alice', 100), ('bob', 100), ('charlie', 100)]

# Pass constant exponent 2 to map(pow, ...):
squared = list(map(pow, [2, 3, 4], itertools.repeat(2)))
print(squared)  # [4, 9, 16]

4. Passing a Single Integer to list(42), .extend(42), or my_list += 42

Developers often assume list(42) wraps 42 into [42], or that my_list.extend(42) / my_list += 42 appends 42 to a list. Under the hood, list(), tuple(), set(), .extend(), and += on a list all iterate over their argument element-by-element.

  • The Trigger (Verified 3.10.16):
# All three lines below raise TypeError: 'int' object is not iterable:
# a = list(42)
items = [1, 2]
items.extend(3)
# items += 3
  • The Fix: Use square brackets [42] to create a single-element list, and use items.append(3) (or items += [3]) to add a single integer to an existing list:
single_list = [42]
items = [1, 2]
items.append(3)
print(single_list, items)  # [42] [1, 2, 3]
  • How to tell it’s this one: The crash points to list(...), tuple(...), set(...), .extend(...), or += on a list variable.

5. Iterating Over or Indexing the Digits of an Integer (not iterable vs. not subscriptable)

When solving math or algorithm problems, a common mistake is treating a multi-digit integer pin = 12345 as if it were a list or string of digits:

  • Looping over the integer (for digit in pin:): Raises TypeError: 'int' object is not iterable.
  • Indexing the integer (pin[0]): Raises its closest sibling error, TypeError: 'int' object is not subscriptable.
  • The Trigger (Verified 3.10.16):
pin = 12345
# Fails with: TypeError: 'int' object is not iterable
for digit in pin:
    print(digit)

# Fails with: TypeError: 'int' object is not subscriptable
first_digit = pin[0]
  • The Fix: Convert the integer to a string with str(pin) first so you can either iterate over its characters or index str(pin)[0], then convert back to int:
pin = 12345
digits = [int(ch) for ch in str(pin)]
first_digit = int(str(pin)[0])
print(digits, "| First:", first_digit)  # [1, 2, 3, 4, 5] | First: 1

6. Shadowing a List Variable with an Integer (scores = sum(scores)) or Missing a Tuple Comma (42)

Two subtle syntax traps turn a variable you thought was a collection into a plain int:

  1. Variable Shadowing: Reusing the same variable name for both a list and a count/sum (scores = [10, 20]; scores = sum(scores)) overwrites the list with the integer 30. Any later for s in scores: loop (or scores[0] lookup) crashes.
  2. Missing Trailing Comma in a 1-Element Tuple ((42) vs. (42,)): In Python, parentheses around a single value (42) are just grouping parentheses and evaluate to the integer 42. To create a 1-element tuple—such as for a loop or threading.Thread(target=fn, args=(42,))—you must include the trailing comma (42,).
  • The Trigger (Verified 3.10.16):
# Trap A: Missing comma makes 'single_tuple' an int (42), not a tuple!
single_tuple = (42)
for x in single_tuple:  # TypeError: 'int' object is not iterable
    print(x)
  • The Fix: Add the trailing comma (42,) (or use a list [42]), and use distinct variable names for totals (total_score = sum(scores)):
single_tuple = (42,)
for x in single_tuple:
    print(x)  # Prints: 42

Can You Fix This TypeError?

scores = [10, 20]
scores.extend(30)
print(scores)

Choose the best fix:

7. Using the in Operator on an Integer (TypeError: argument of type 'int' is not iterable)

When you test membership with if x in target: and target is an int instead of a list, tuple, or set, Python raises a slightly worded variant: TypeError: argument of type 'int' is not iterable.

  • The Trigger (Verified 3.10.16):
allowed_roles = 1  # Accidentally an int instead of [1, 2]
if 1 in allowed_roles:
    print("Access granted")
# TypeError: argument of type 'int' is not iterable
  • The Fix: Use == if comparing two integers (if role == 1:), or store multiple allowed values in a collection like {1, 2} or (1, 2):
allowed_roles = {1, 2}
if 1 in allowed_roles:
    print("Access granted")

8. Generator yield from and Star-Unpacking (*x) on an Integer

In Python generators and unpacking expressions, delegating to or unpacking a scalar integer triggers immediate iteration errors:

  1. yield from in a Generator (yield from 42): While yield 42 yields the single integer 42, yield from sub_iterable is designed to delegate to another generator or iterable collection. Writing yield from 42 calls iter(42) and raises TypeError: 'int' object is not iterable.
  2. Iterable Unpacking in Literals, Assignments, and Calls:
    • Unpacking inside a set literal ({1, *42}) raises TypeError: 'int' object is not iterable.
    • Unpacking inside a list or tuple literal ([1, *42] or (1, *42)) raises TypeError: Value after * must be an iterable, not int.
    • Multiple assignment (a, b = 42 or a, *b = 42) raises TypeError: cannot unpack non-iterable int object.
    • Function argument unpacking (fn(*42)) raises TypeError: fn() argument after * must be an iterable, not int.
  • The Trigger (Verified 3.10.16):
def generate_ids():
    yield from 101  # Fails: TypeError: 'int' object is not iterable

list(generate_ids())
  • The Fix: Use plain yield 101 to emit a single value from a generator, or pass an iterable sequence to yield from [101, 102]:
def generate_ids():
    yield 101              # Yields one integer
    yield from [102, 103]  # Yields each item from the list

print(list(generate_ids()))  # [101, 102, 103]

9. Pandas & NumPy Scalar Traps (.apply(sum), .item(), .iloc[0], and np.int64)

In Pandas 2.0.0 and NumPy 1.26.3, two distinct patterns trigger non-iterable integer crashes:

Pattern A: Calling df["price"].apply(sum) on a Series

Calling df["price"].apply(sum) on an integer Series does not sum the column—instead, Series.apply() loops over the column and calls Python’s built-in sum(x) on each individual integer cell (sum(10)), crashing on the very first row!

  • The Trigger & Fix (Verified Pandas 2.0.0):
import pandas as pd

df = pd.DataFrame({"price": [10, 20, 30]})
# Fails: calls sum(10) on the first integer cell!
# total = df["price"].apply(sum)  # TypeError: 'int' object is not iterable

# Fix: Call the vectorized Pandas Series .sum() method
total = df["price"].sum()
print(total)  # Prints: 60

Pattern B: Iterating df["col"] vs. .values vs. .item() and numpy.int64

When extracting data from a DataFrame column, the method you call determines whether you get an iterable sequence, a native Python int, or a numpy.int64 scalar (note that in Python 3, np.int64 is not a subclass of built-in int—issubclass(np.int64, int) is False—yet it fails the exact same way when iterated):

import pandas as pd

df = pd.DataFrame({"col": [42]})

for x in df["col"]:          # Works: iterates over the Pandas Series (yields 42)
    pass

for x in df["col"].values:   # Works: iterates over the 1D NumPy int64 ndarray (yields 42)
    pass

# Fails: .item() unboxes a 1-element Series to a native Python int (42)
for x in df["col"].item():   # TypeError: 'int' object is not iterable
    pass

# Fails: .iloc[0] (or .values[0]) returns a scalar numpy.int64 object
for x in df["col"].iloc[0]:  # TypeError: 'numpy.int64' object is not iterable
    pass

Custom Functions Returning Unexpected Types (APIs, Databases & Multi-Path Returns)

In production applications, TypeError: 'int' object is not iterable rarely comes from a hardcoded for i in 5:. Instead, it happens when a function or external data source usually returns a list, but returns an integer under specific edge cases:

  1. API Responses Returning Unexpected Types: Weakly typed REST APIs or legacy backends sometimes return a JSON array of objects when results exist ({"users": [{"id": 1}]}), but return the integer 0 ({"users": 0}) or an HTTP error code (404) when no items match. Always validate isinstance(payload.get("users"), list) at the API boundary before iterating.
  2. Database & ORM Queries (.count() vs. .all() and rowcount):
    • In Django ORM (not run by me; noted from documentation), calling User.objects.filter(is_active=True).count() returns an int, whereas .all() or .filter() returns an iterable QuerySet. Passing a .count() variable into a template {% for user in active_users %} or serializer loop crashes with:
Traceback (most recent call last):
  File "/var/www/app/views/reports.py", line 28, in export_active_users
    emails = [u.email for u in active_users]
TypeError: 'int' object is not iterable
  • In DB-API drivers (sqlite3, psycopg2, pymysql), cursor.rowcount is an integer count of affected rows, whereas cursor.fetchall() returns the list of row tuples.

3. Functions with Multiple Return Paths: A function that has an early guard clause returning a C-style sentinel integer (if error: return -1 or if not found: return 0) while its main path returns a list creates a ticking time bomb for callers.

4. Optional Collection Results vs. Required Data:

  • When empty results are normal (Optional): Return an empty list [] (or empty tuple ()) across every non-error branch so for item in get_items(): simply runs zero times.
  • When failures occur (Required): Raise an explicit exception (raise ValueError(...) or raise RuntimeError(...)) instead of returning -1 or 0.

5. Enforcing Consistent Return Type Annotations: Annotate collection-returning functions with -> list[dict[str, Any]]: or -> Sequence[int]: so static type checkers flag any return 0 branch immediately.

None vs. Integers: Comparing 'NoneType' and 'int' Non-Iterable Bugs

TypeError: 'int' object is not iterable and TypeError: 'NoneType' object is not iterable crash at the exact same consumption point (such as for x in result:), but they point to completely different mistakes in the function that produced result:

AspectTypeError: ‘int’ object is not iterableTypeError: ‘NoneType’ object is not iterable
Runtime Value of VariableAn integer like 0, -1, 1, 404, or len(items).None (Python’s singleton null value).
Most Common Root CauseCalling len(items) instead of range(len(items)), returning a C-style status code (return 0 / return -1), calling ORM .count() instead of .all(), or overwriting a list variable with sum().Forgetting a return statement on an if/else branch, or assigning an in-place method back to a variable (items = items.sort() or items = items.append(x)).
How to Fix the ProducerReplace return 0 with return [] (for optional empty data) or raise ValueError(...) (for errors), or wrap counts in range().Ensure every execution path in your function explicitly returns a list/tuple, and never assign .sort() or .append() back to the list variable.

Sibling Non-Iterable & Integer TypeError Variants

Depending on the exact syntax or type that triggered the crash, Python raises several closely related TypeError messages (all verified on Python 3.10.16 and NumPy 1.26.3):

Error Message Variant (Verified 3.10.16)What Triggered ItThe Fix
TypeError: 'numpy.int64' object is not iterableIterating over a scalar extracted from a NumPy array or Pandas Series (for x in df["col"].iloc[0]: or for x in arr[0]:).Iterate over the Series/array itself (for x in df["col"]:), or wrap the scalar in range(int(val)).
TypeError: 'int' object is not subscriptableIndexing or slicing an integer with square brackets (pin = 12345; pin[0]), or indexing a list variable that was overwritten by an int.Convert to a string before indexing (str(pin)[0]), or stop shadowing your list/dict variable with an integer.
TypeError: 'float' object cannot be interpreted as an integerPassing a float or / division result into range() (range(3.5) or range(10 / 2)).Use floor division // (range(10 // 2)), int(x), or numpy.arange(0, 3.5, 0.5) for decimal steps.
TypeError: argument of type 'int' is not iterableMembership test using in or not in where the right operand is an integer (5 in 15).Use == to compare two integers, or change the right side to a set/list (5 in {5, 15}).
TypeError: cannot unpack non-iterable int objectMultiple assignment from a single integer (x, y = 42 or a, *b = 42).Assign to a single variable (x = 42), or return a tuple (42, 0) from the function.
TypeError: Value after * must be an iterable, not intStar-unpacking an integer inside a list or tuple literal ([1, *42] or (1, *42)).Remove the * to include a single integer ([1, 42]), or unpack an iterable collection ([1, *items]).
TypeError: fn() argument after * must be an iterable, not intUnpacking an integer with * in a function call (fn(*42) or threading.Thread(target=fn, args=(42))).Add a trailing comma to 1-element tuples (args=(42,)), or remove the * if passing one integer.
TypeError: 'float' object is not iterableLooping over a float (for x in 3.14:) or calling sum(3.14) / list(3.14).For decimal steps in a loop, use numpy.arange(0, 1.0, 0.1) or linspace().
TypeError: 'bool' object is not iterableLooping over True or False (when a function returned False on failure instead of []).Return an empty list [] instead of False from functions that return collections.
TypeError: 'NoneType' object is not iterableLooping over None (for x in my_list.sort(): or a function with a missing return).Never assign my_list = my_list.sort(), and ensure functions return [] instead of None.
TypeError: object of type 'int' has no len()Calling len(42) on an integer (often thinking it returns the number of digits).To count digits in an integer, convert to string first: len(str(abs(42))).

Catch Non-Iterable Integer Bugs Before Runtime with Linters

Static analysis tools and type checkers detect attempts to iterate over or unpack integers in your IDE before you ever run the script (linter and type checker outputs noted from documentation):

def get_ids(flag: bool) -> list[int] | int:
    return [101, 102] if flag else 0

for uid in get_ids(False):  # <-- Flagged in IDE before runtime!
    print(uid)

Here is what each tool reports on line 4 above:

  • Mypy: error: Item "int" of "list[int] | int" has no attribute "__iter__" (not iterable) [union-attr] (or error: "int" object is not iterable [misc] when iterating a pure int).
  • Pyright / Pylance (VS Code): Type "int" is not iterable (reportGeneralTypeIssues)
  • Pylint: E1133: Non-iterable value get_ids(False) is used in an iterating context (not-an-iterable)

How to Resolve the Warning Cleanly (Without # type: ignore): Never silence for uid in get_ids(False): # type: ignore[union-attr]—that only hides the exact runtime crash waiting to happen when flag is False. Instead:

  1. Fix the return signature (Best): Change get_ids(flag: bool) -> list[int]: so the False branch returns [] instead of 0.
  2. Narrow the union type: If you cannot modify get_ids() (for example, it comes from a third-party library), narrow the type with isinstance() before looping:
result = get_ids(False)
if isinstance(result, list):
    for uid in result:
        print(uid)

Worked Example: Fixing a Webhook Pipeline That Defaults to 0 Instead of []

Let’s walk through a realistic multi-frame stack trace from a webhook sync service (/var/www/app/services/webhook_sync.py) where an empty batch payload returns {"users": 0} (or falls back to .get("users", 0)), crashing the downstream batch loop.

The Code (/var/www/app/services/webhook_sync.py):

import json

def extract_user_ids(payload):
    return payload.get("users", 0)

def sync_account_batch(payload):
    user_ids = extract_user_ids(payload)
    synced = []
    for uid in user_ids:
        synced.append(int(uid))
    return synced

def handle_webhook(raw_body):
    payload = json.loads(raw_body)
    return sync_account_batch(payload)

handle_webhook('{"event": "batch.sync", "users": 0}')

Verified Traceback (Python 3.10.16):

Traceback (most recent call last):
  File "/var/www/app/services/webhook_sync.py", line 17, in <module>
    handle_webhook('{"event": "batch.sync", "users": 0}')
  File "/var/www/app/services/webhook_sync.py", line 15, in handle_webhook
    return sync_account_batch(payload)
  File "/var/www/app/services/webhook_sync.py", line 9, in sync_account_batch
    for uid in user_ids:
TypeError: 'int' object is not iterable

The Thought Process & Fix:

  1. Reading the traceback from bottom to top, the crash happens in sync_account_batch on line 9 (for uid in user_ids:).
  2. Tracing user_ids back to extract_user_ids(payload), we see two bugs: .get("users", 0) uses the integer 0 as its fallback default, and the external webhook payload itself sent "users": 0 when the batch was empty.
  3. The Result: Fix extract_user_ids() at the boundary so it defaults to [] and normalizes 0 / None (for optional empty batches) or raises a clear ValueError (when a non-empty list is strictly required):
import json

# Approach A (Optional batch): Default to [] and coerce 0/None to []
def extract_user_ids_optional(payload):
    users = payload.get("users")
    if not users:
        return []
    if not isinstance(users, list):
        raise ValueError(f"Expected 'users' to be a list, got {type(users).__name__}: {users!r}")
    return users

# Approach B (Required batch): Require a non-empty list of user IDs
def extract_user_ids_strict(payload):
    users = payload.get("users")
    if not isinstance(users, list) or not users:
        raise ValueError(f"Webhook payload requires a non-empty 'users' list, got: {users!r}")
    return users

sample = json.loads('{"event": "batch.sync", "users": 0}')
print("Optional empty batch:", extract_user_ids_optional(sample))
# Verified Output: Optional empty batch: []

Can You Fix This TypeError?

df = pd.DataFrame({"price": [10, 20, 30]})
total = df["price"].apply(sum)
print(total)

Choose the best fix:

Frequently Asked Questions

Why does max(10, 20) work in Python, while sum(10, 20) raises TypeError: 'int' object is not iterable?

max() and min() have two overloaded signatures: max(iterable) and max(arg1, arg2, *args). When you pass two arguments (max(10, 20)), Python compares them directly. Built-in sum(iterable, start=0) only has one signature: its first argument must be an iterable, and its second argument is the starting number. Use 10 + 20 or sum([10, 20]).

Why is range(-5) or range(0) valid in a for loop, while for i in -5: raises a TypeError?

range(-5) and range(0) construct a valid range iterable object whose start (0) is already greater than or equal to its stop (-5 or 0), so the loop cleanly executes zero times (list(range(-5)) is []). By contrast, for i in -5: tries to call iter(-5) on the integer -5 itself, which fails because integers are not iterable.

What is the difference between 'int' object is not iterable and 'int' object is not subscriptable?

TypeError: 'int' object is not iterable happens when you try to loop over or unpack an integer (for x in 123: or list(123)). TypeError: 'int' object is not subscriptable happens when you try to access an index or key on an integer using square brackets (123[0]). If you wanted to inspect individual digits, convert the integer to a string first (str(123)[0]).

Why did map(str, 42) or enumerate(5) fail immediately before my for loop even started?

Although map(), filter(), zip(), and enumerate() return lazy iterators, CPython calls iter() on their input arguments at the moment the iterator is constructed. Always pass a collection like [42] or range(5) into these functions.

Similar Posts

Leave a Reply