TypeError: can’t multiply sequence by non-int of type ‘float’

Loading

The error message:

TypeError: can't multiply sequence by non-int of type 'float'

occurs when you try to multiply a sequence (like a list or string) by a float instead of an integer.


1. Causes and Solutions

Cause 1: Multiplying a String or List by a Float

Python allows repeating sequences using multiplication, but only by an integer. Multiplying by a float raises an error.

Incorrect Code:

text = "Hello"
print(text * 2.5) # TypeError
numbers = [1, 2, 3]
print(numbers * 1.5) # TypeError

Solution: Use an Integer for Multiplication

print(text * 2)  # Output: HelloHello
print(numbers * 3) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Alternative: Convert Float to Integer

If you want a rounded repeat, convert the float to an integer.

print(text * int(2.5))  # Output: HelloHello

Cause 2: Using a Float in a Loop Repetition (* Operator)

If you’re trying to initialize a list with repeated values but use a float, you’ll get this error.

Incorrect Code:

arr = [0] * 2.5  # TypeError

Solution: Convert the Float to an Integer

arr = [0] * int(2.5)  # Works correctly
print(arr) # Output: [0, 0]

Cause 3: Accidentally Using Float in Mathematical Operations with a Sequence

If a float is unintentionally introduced into an expression with a sequence, Python will raise this error.

Incorrect Code:

num_repeats = 4 / 2  # This is a float (2.0)
text = "Hi"
print(text * num_repeats) # TypeError

Solution: Convert to an Integer

num_repeats = int(4 / 2)
print(text * num_repeats) # Output: HiHi

Leave a Reply

Your email address will not be published. Required fields are marked *