Skip to main content

How to Resolve Python "TypeError: int() argument must be a string... not 'NoneType' / 'list'"

The int() constructor in Python is used to convert values into integers. However, it has specific requirements for its input. You'll encounter a TypeError: int() argument must be a string, a bytes-like object or a real number, not 'X' (where X is often 'NoneType', 'list', or another incompatible type) if you attempt to convert an object of type X directly to an integer when int() doesn't support that conversion.

This guide explains why these errors occur, focusing on NoneType and list, and provides solutions for correctly handling these types before conversion.

Understanding the Error: What int() Accepts

The built-in int() function can create integer objects from:

  • Numbers: Other real numbers like integers (int) or floats (float) (truncating floats towards zero).
  • Strings: Strings that represent whole numbers (e.g., "123", "-45"). It can handle leading/trailing whitespace but not non-numeric characters (except a leading sign).
  • Bytes-like objects: Similar to strings, if they represent numbers in the correct encoding/base.

Crucially, int() cannot directly convert objects like None, lists, dictionaries, or sets into a single integer value because there's no obvious, standard numerical representation for these types.

Cause 1: Passing None to int() (...not 'NoneType')

This error occurs when the variable or value passed to int() holds the None object.

Error Scenario

value = None
print(f"Type of value: {type(value)}") # Output: <class 'NoneType'>

try:
# ⛔️ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
number = int(value)
print(number)
except TypeError as e:
print(e)

int() doesn't know how to interpret None as a number.

Common Sources of None

Variables often become None unexpectedly due to:

  • Functions returning None implicitly (no return) or explicitly.
  • Functions returning None conditionally (e.g., search fails).
  • Assigning the result of in-place methods like list.sort() (which return None).
  • Explicit assignment: my_var = None.

Solution: Provide a Default Value (e.g., 0)

Use the or operator to provide a default numeric value (like 0) if the variable is None before passing it to int().

value = None

# ✅ Use 'or 0' to substitute 0 if value is None
number = int(value or 0)
print(f"Result (with fallback 0): {number}")
# Output: Result (with fallback 0): 0

value_from_func = None # Assume a function returned None
number_from_func = int(value_from_func or 0)
print(f"Result from func (fallback 0): {number_from_func}")
# Output: Result from func (fallback 0): 0

Output:

Result (with fallback 0): 0
Result from func (fallback 0): 0
  • value or 0 evaluates to 0 if value is None (or any other "falsy" value like False, 0, ""). If value holds a "truthy" value (like a non-empty string representing a number), that value is used.

Solution: Check for None Before Calling int()

Explicitly check if the variable is None and handle that case separately, only calling int() when you have a valid input.

value = None
number = 0 # Initialize with a default

# ✅ Check for None before conversion
if value is not None:
try:
number = int(value) # Only call int() if value is not None
print("Conversion successful.")
except (ValueError, TypeError) as e: # Catch potential conversion errors too
print(f"Error converting non-None value '{value}': {e}")
else:
print("Value is None, using default 0.") # This is executed

print(f"Final number: {number}") # Output: Final number: 0

Output:

Value is None, using default 0.
Final number: 0

Cause 2: Passing a list to int() (...not 'list')

This error occurs when you pass an entire list object to the int() constructor.

Error Scenario

data = ['1', '2', '3'] # A list of strings
print(f"Type of data: {type(data)}") # Output: <class 'list'>

try:
# ⛔️ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'
number = int(data)
print(number)
except TypeError as e:
print(e)
note

int() can not convert the whole list structure into a single integer.

Solution: Convert a Specific List Element

If you intend to convert a specific item within the list (assuming that item is a number string or a number), access it using its index first.

data = ['100', '200', '300']

# ✅ Convert the first element (index 0)
try:
first_number = int(data[0])
print(f"First number: {first_number}") # Output: First number: 100
except IndexError:
print("List is empty.")
except ValueError:
print(f"Element at index 0 ('{data[0]}') is not a valid integer string.")

Solution: Join List Elements into a String First

If your list contains digit strings and you want to treat them as digits of a single number (e.g., ['1', '2', '3'] becomes 123), first join the list elements into a single string, then convert that string.

digit_strings = ['1', '2', '3']

# ✅ Join the strings
joined_string = "".join(digit_strings)
print(f"Joined string: '{joined_string}'") # Output: Joined string: '123'

# ✅ Convert the joined string to int
number = int(joined_string)
print(f"Resulting number: {number}") # Output: Resulting number: 123

# Handle list with mixed types (needs str conversion before join)
mixed_data = ['4', 5, '6']
joined_mixed = "".join(str(item) for item in mixed_data) # Convert each item to str first
number_mixed = int(joined_mixed)
print(f"Joined mixed string: '{joined_mixed}'") # Output: '456'
print(f"Resulting mixed number: {number_mixed}") # Output: 456

Output:

Joined string: '123'
Resulting number: 123
Joined mixed string: '456'
Resulting mixed number: 456
  • "".join(...): Concatenates the elements of the iterable into a single string. Requires elements to be strings (use str(item) if needed).

Solution: Convert Each Element Using List Comprehension/map()

If you want to convert every string element in the list into its own integer, creating a new list of integers, use a list comprehension or map().

string_nums = ['10', '25', '-5']

# ✅ Using list comprehension
int_list_comp = [int(s) for s in string_nums]
print(f"List of ints (comp): {int_list_comp}") # Output: [10, 25, -5]

# ✅ Using map()
int_list_map = list(map(int, string_nums))
print(f"List of ints (map): {int_list_map}") # Output: [10, 25, -5]

Output:

List of ints (comp): [10, 25, -5]
List of ints (map): [10, 25, -5]

This creates a list of integers, not a single integer.

Debugging the Error (type())

When you get this TypeError from int():

  1. Identify the variable being passed to int().
  2. Print its type immediately before the call: print(type(variable_to_convert)).
  3. The output will show the problematic type (<class 'NoneType'>, <class 'list'>, etc.) instead of the expected <class 'str'>, <class 'int'>, or <class 'float'>.
  4. Trace back to see where that variable received the unexpected type.

Conclusion

The TypeError: int() argument must be a string, a bytes-like object or a real number, not 'X' means you tried to convert an invalid type X (like NoneType or list) directly to an integer using int().

To resolve this:

  • If the input is None: Check for None before calling int() or provide a default numeric value using int(variable or 0). Address the source of the None value if it was unexpected.
  • If the input is a list:
    • Access the specific element you want to convert using indexing (int(my_list[index])).
    • Join the elements into a single string first (int("".join(str(x) for x in my_list))) if they represent digits of one number.
    • Use a list comprehension ([int(x) for x in my_list]) or map(int, my_list) to convert each element into a new list of integers.

Always ensure the value passed to int() is a number, a string representing a whole number, or a bytes-like object representing a number before attempting the conversion.