Python

typeerror: can’t multiply sequence by non-int of type ‘float’ ( Solved )

typeerror: can’t multiply sequence by non-int of type ‘float’ error occurs while multiplying any string or array to any float value. See! The golden and most simple rule is that multiplication is possible in numeric values. We can keep both the operand Decimals( Float ) or whole numbers ( Integer). But if one operand is a sequence like string or array then it is mandatory that the second must be Integer only.  In this article, We will understand the root cause and correspondence easiest way to fix this.

typeerror: can’t multiply sequence by non-int of type ‘float’ ( Root Cause ) –

The best way to understand the root cause of this error is replication. We will take a practical scenario where the Interpreter throws the same error.

my_list=[1,2,3]
coff=4.2
multiply=my_list*coff
print(multiply)

Here we have taken a list (my_list ) which is a python sequence. When we tried to multiply the same with non-integer value float (coff), we get this can’t multiply sequence by non-int of type ‘float’.

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

Solution –

There are two generic scenarios for which the developer wrote this code. In this section, we will understand and then fix them accordingly.

Scenario 1: Intent to multiply the sequence –

In this scenario, the intent is to multiply the sequence by a number. But if the number is non-integer then we get this error. The best way to fix this typecast the double or float to integer. Then for multiplication.

typecasting float to int

Scenario 2: Intent to multiply the individual elements of the sequence –

Unlike the above, There can be a possibility where we want to multiply any non-integer value to each element of the python sequence but we end up at this error.  Let’s take an example of this-

non-integer sequence multiplication error

The best way to fix this error is by using a loop. We have to iterate three sequences and then multiply the coefficient with each element and then reassign them into the same sequence or array. Here is an example of this.

solution – non integer sequence multiplication error

Other Scenarios :

Case 1. Multiplication with non-int with String as python sequence –

my_str="ABC"
coff=4.2
multiply=my_str*coff
print(multiply)
multiply sequence by non-int of type ‘float’

Case 2. Multiplication with non-int with a tuple as python sequence –

my_tuple=(1,2,3)
coff=4.2
multiply=my_tuple*coff
print(multiply)
multiply sequence TUPLE by non-int of type ‘float’

Conclusion –

This scenario has many variants of similar typeerror like –

and many more. But the root cause and base of the solution will always be safe.

 

Thanks

Data Science Learner Team