Fix the typerror can’t multiply sequence by float in Python

In today’s short tutorial we’ll help you troubleshoot a type error that you might receive when trying to multiply a sequence (strings, lists or tuples) by a float number in Python.

Can’t multiple sequence by float error

Let’s run the following code:

#this will result in a string
product_price = input ("Enter the product price")

#this is a floating number
order_discount = 0.1

total_cost = product_price * order_discount
print (total_cost)

After entering the product price, as expected, we’ll get the following error:

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

Fixing the error

The meaning of the error we got is that although Python is able to multiple a string by an integer, it can’t obviously multiple it by a float number.

Luckily, fixing this is quite simple, we can cast the product_price variable into a float:

product_price = float (input ("Enter the product price"))
order_discount = 0.1

total_cost = product_price * order_discount
print (total_cost)

Multiplying a list sequence by a float number

Similar to strings and tuples, lists are also considered a sequence object in Python. Hence trying to multiply a list by a float will also throw a type error.

Run the following code:

my_list = [1,2,3,4]

order_discount= 0.1


my_list*order_discount

You can fix this using the numpy library array object:

# first off, import Numpy to your workspace
import numpy as np

# convert the list to an array
my_array = np.array(my_list)
order_discount= 0.1

# multiply the array by the float
my_array*order_discount

And the result will be:

array([0.1, 0.2, 0.3, 0.4])