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?
try... exceptis 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.