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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "TypeError: can't multiply sequence by non-int of type list" occurs when we try to multiply a sequence (e.g. a list or a string) by a list object. To solve the error, correct the assignment to an int to be able to use the multiplication operator.

typeerror cant multiply sequence by non int of type list

Here is an example of how the error occurs.

main.py
my_list_1 = [1, 2, 3] my_list_2 = [4, 5, 6] # ⛔️ TypeError: can't multiply sequence by non-int of type 'list' result = my_list_1 * my_list_2

We are trying to multiply a list by another list which is not allowed.

You could multiply a list (or another sequence) by an integer if you need to duplicate the items in the list N times.

main.py
my_list_1 = [1, 2, 3] result = my_list_1 * 2 print(result) # 👉️ [1, 2, 3, 1, 2, 3]

If you need to multiply each value in a list by a number, use a list comprehension.

main.py
my_list = [1, 2, 3] result = [x * 2 for x in my_list] print(result) # 👉️ [2, 4, 6]

We used a list comprehension to multiply each item in the list by 2.

If you use numpy, you can achieve the same result in a more direct way.

main.py
import numpy as np arr = np.array([1, 2, 3]) result = arr * 2 print(result) # 👉️ [2, 4, 6]

You can directly multiply a numpy array with an integer to multiply each item in the array.

When you use the multiplication operator, you have to make sure that at least one of the values is an integer.

If you aren't sure what type of object a variable stores, use the type() class.

main.py
my_list = [1, 2, 3] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True my_int = 5 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: can't multiply sequence by non-int of type list" occurs when we try to multiply a sequence (e.g. a list or a string) by a list object. To solve the error, correct the assignment to an int to be able to use the multiplication operator.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.