Lately, I haven’t been writing a lot of code, but I have gotten a chance to review some code. Naturally, that comes with the honor of searching for bugs which is where I found the inspiration for this article. Specifically, I ran into the following TypeError: can’t multiply sequence by non-int of type ‘str’.
In general, this TypeError occurs when a sequence like a list or string is duplicated using the multiplication operator. Of course, for the error to occur, the value that the sequence is scaled by must not be an integer. In this case, it’s a string, but it could be anything. To fix it, we’ll need to identify the incorrect value and convert it to an integer.
For more details, keep reading! However, if this is all you needed, I’d appreciate it if you took the time to support the site. Thanks for your help!
Table of Contents
What Is a TypeError?
According to the Python documentation, a TypeError is:
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise.
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.Python 3.8.4rc1 Docs, 07/03/2020
Of course, I tend to prefer a definition that isn’t so full of jargon. In other words, a TypeError occurs when we’re doing something that our data doesn’t support. For example, we might have a function that adds numbers together. If for some reason, we supply values that aren’t numbers—say strings or lists—we’d expect the function to fail with a TypeError.
For those of us used to statically typed languages like Java or C, a TypeError is a lot like a type checking error during compilation. After all, languages like that won’t even compile if there is a type mismatch. Unfortunately, Python doesn’t really have the luxury of type checking until runtime, so TypeError takes its place.
That said, we’re not here to talk TypeErrors in general. We have a very specific error message that we’d like to dissect. Let’s take a look in the next section.
What Does This TypeError Message Mean?
Today, we’re interested in talking about the following TypeError message:
TypeError: can't multiply sequence by non-int of type 'str'
At first glance, this error message appears to be stating that some form of multiplication is failing because one of the values isn’t an integer. In addition, the other value is a sequence like a string or list. In other words, we must be trying to use the multiplication operator to duplicate a sequence. However, the scaling factor is not an integer—it’s a string.
Now, it’s possible that your error message reads a little differently. In fact, I suspect that this error message will vary slightly depending on the type of the value that’s incorrect. In my case, it’s a string. In your case, it could be some other data type like a list or tuple.
For simplicity, I have an example of the string problem. In fact, I most recently ran into this error during a code review where I saw the following code snippet:
number = input("Enter a number >>> ") sign = number value = number[1:] if sign == '+': print('+' * value) else: print('-' * value)
When executed correctly, it reports the following error:
Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> '+' * value TypeError: can't multiply sequence by non-int of type 'str'
Clearly, the only line this message could apply to is one of the following:
print('+' * value) print('-' * value)
After all, these are the only two lines that contain any multiplication. Fortunately, this error gives us yet another hint at which line it could be talking about: `’+’ * value`python. In other words, the error appears to be occurring in the plus sign line.
Of course, knowing where the error is occurring is only half the battle. Now, we need to understand why the program is failing at this point. Luckily, the error message says the following: `can’t multiply sequence by non-int of type ‘str’.`python
If we read into this message a bit, it states that we’re unable to multiply two things together because one of them is of the wrong type. In this case, one of our values needs to be an integer. Since the value on the left is a string constant, we can probably assume that’s not the incorrect value. Instead, it’s `value`python.
At this point, we need to trace back up the code to see where `value`python is defined and used. As far as I can tell, it’s only defined once as a function of another variable, `number`python.
In this case, `number`python is a string that we request from the user. When we use it to define `value`python, we take a subset of it. As a result, `value`python must also be a string. That explains the error we’re getting!
Now that we know what’s causing the error, it’s just a matter of fixing it. In the next section, we’ll take a look at a fix.
How to Fix This TypeError?
Fortunately, this type of error has an easy fix. As long as we know which variable is the wrong type, we can find a way to convert it. In our case, it’s a matter of casting `value`python to an integer before using it:
number = input("Enter a number >>> ") sign = number value = int(number[1:]) if sign == '+': print('+' * value) else: print('-' * value)
Now, when we get down to the section with the bug, we should expect to get the correct output:
>>> number = input("Enter a number >>> ") Enter a number >>> -17 >>> sign = number >>> value = int(number[1:]) >>> if sign == '+': print('+' * value) else: print('-' * value) -----------------
Of course, you’re situation might be a bit different. As a result, you’ll have to figure out what value is taking on the wrong type. Then, you’ll have to find a way to convert it as needed. Naturally, that depends on the type of data you’re working with, so it could be as simple as a function call or as difficult as some data transformation.
Need Help Fixing This TypeError?
As always, it’s tough for me to anticipate what your bug is, so it’s unlikely my example maps exactly to yours. As a result, I’d like to extend my hand in support. If this article wasn’t enough for you, consider reaching out!
One of the ways you can get a hold of me is with the hashtag #RenegadePython on Twitter. Typically, I use that space for Python challenges, but I’m also happy to use that space for bug hunting! For instance, here’s some sample code that will cause this bug:
Feel free to piggyback off this thread with your problem or start your own. Either way, I’ll try to lend a hand.
At any rate, that’s all I have today! If you liked this article, and you’d like to read more like it, check out some of these other error articles:
Likewise, here are some helpful resources from Amazon (ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
Finally, you can take your support to the next level by hopping by checking out this list of ways to grow the site. There, you’ll find links to my mailing list, GitHub organization, Patreon, and much more.
Otherwise, thanks for checking this site out! I appreciate your time, and I hope you’ll stick around.
Life has given me a bit of a beating, so I'm taking some time to recover. See y'all again soon.
Why Is Adding Two Random Numbers Not the Same as Generating One in the Same Range?
Generating random numbers might seem easy at first, but there are definitely some pitfalls.