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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

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

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 tuple 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 tuple

Here is an example of how the error occurs.

main.py
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.

main.py
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:

  • Using a pair of parenthesis () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor
Make sure you don't have any trailing commas, e.g. 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.

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.

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_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.

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

Use the search field on my Home Page to filter through my more than 3,000 articles.