Last updated: Apr 20, 2022
Check out my new book
The Python "TypeError: can't multiply sequence by non-int of type tuple"
occurs when we try to multiply a sequence (e.g. a list or a string) by a
object. To solve the error, correct the assignment to an int to be able to use
the multiplication operator.
Here is an example of how the error occurs.
my_list = [1, 2] my_tuple = 3, # ⛔️ TypeError: can't multiply sequence by non-int of type 'tuple' print(my_list * my_tuple)
We are trying to multiply a list by a tuple which is not allowed.
You could multiply a list (or another sequence, e.g. a string or a tuple) by an integer if you need to duplicate the items in the list N times.
my_list = [1, 2] my_int = 3 # 👇️ [1, 2, 1, 2, 1, 2] print(my_list * my_int) print('abc' * 2) # 👉️ 'abcabc'
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()creates an empty tuple
x = 5,because that declares a tuple, not an integer.
If you need to multiply each value in a list by a number, use a list comprehension.
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
If you aren't sure what type of object a variable stores, use the
my_tuple = (1, 2, 3) print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_int = 10 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True
The type class returns the type of an object.
True if the passed in object is an instance or a subclass of
the passed in class.