0

I have this code to create a function to insert to a tuple in python:

   def insert_t(t, i, v):
      l = list(t)
      l.insert(i, v)
      tu = tuple(l)
      return tu

The code works, but there is one problem. Passing t to be any sequence type variable works. But I want t to be only a tuple, not a list or a string. See below for what I mean:

x = 'Hello'
insert_t(x, 2, 4)

The code works for when x is a string, however, this breaks the purpose of the code to append to only tuple. I would like it to raise TypeError if the parameter t is not a tuple.

After looking online, I found that try...except exists, which can raise the required error. However, I don't know how to implement it, since as you can see, I have never used try...except before. How do I implement it?

1
  • try... except is for handling the error. To raise the error, you use... raise. Which is why it's called that. I don't know where you "looked online", but all of this is explained painstakingly, in tutorial form, in the official documentation. Commented Nov 18, 2021 at 18:32

1 Answer 1

2

At its most basic, you're asking for:

if not isinstance(t, tuple):
    raise TypeError

What do you want to have happen when you get the TypeError?


To answer the question raised below. Somewhere else in your code, you will write:

try:
   ... 
   code that might generate a TypeError, possibly right here
   or possibly in some function that is called.
   ...
except TypeError:
   print(...)

Your try/except should be somewhere that you can actually deal with the error and sensibly continue.

Sign up to request clarification or add additional context in comments.

1 Comment

I just want to print a message saying 'Invalid Data type - Expected tuple, got' string or list depending upon the value of t passed