1
def copy_list(t):
try:
    if type(t) is list:
        t_copy=[]
        n=len(t)
        i=0
        while i<n:
            t_copy.append(t[i])
            i+=1
        return t_copy
except TypeError:
        return "Not a list"

The problem says that I should write a function which takes a list of integers as an input and returns a copy of it. It should raise an exception if the input is not a list. I am unable to understand that why my code is unable to raise an exception if the value is not of the list type or when the input is None?

  • 3
    Because your `if` statement will only trigger on `t` being a list, none of the other statements will try to run on non lists, so you never hit any code that will raise an exemption. – Morgan Thrapp Oct 27 '15 at 14:56
  • 1
    You're catching `TypeError`; which line in the `try` block do you expect to throw that exception? (Furthermore, since you're *catching* the exception, you're violating the stipulation that your function should *throw* an exception. Since the function is supposed to throw, you shouldn't catch errors there.) – Rob Kennedy Oct 27 '15 at 14:57
  • So how can I modify my code in order to reach the except statement? – Varun Upadhyay Oct 27 '15 at 14:57
  • 1
    This is not a good use of `try..except` . Just `if..else` should be sufficient. – karthikr Oct 27 '15 at 14:57
  • @karthikr I used a if-else also but it is not able to check for None input – Varun Upadhyay Oct 27 '15 at 15:06
  • 1
    Perhaps they want you to use `assert type(t) is list`. – meuh Oct 27 '15 at 15:07
  • [How to clone or copy a list in Python?](http://stackoverflow.com/q/2612802/33732) – Rob Kennedy Oct 27 '15 at 15:07

3 Answers3

0

Your code doesn't raise an exception because you check whether the type of t is a list using if type(t) is list. When you provide None as an input, it doesn't pass the if statement and falls through so nothing is returned and no exception is raised.

You can remove the if statement to raise your exception. n=len(t) will trigger the exception, as you cannot get the length of None (TypeError: object of type 'NoneType' has no len() ), and "Not a list" will be returned.

try:
    t_copy=[]
    n=len(t)
    i=0
    while i<n:
        t_copy.append(t[i])
        i+=1
    return t_copy
except TypeError:
    return "Not a list"
Robert Lacher
  • 656
  • 1
  • 6
  • 16
0

Just throw it into a for loop, the if type should catch anything else.

def copy_list(t):
    if type(t) is list:
        t_copy=[]
        for i in t:
            t_copy.append(i)
        return t_copy
    else:
        return "Not a list"
y = None
x = copy_list(y)
print x
y = "abc"
x = copy_list(y)
print x
y = [1,2,3,4,5,6,7,8,9]
x = copy_list(y)
print x

Or more succinctly:

def copy_list(t):
    if type(t) is list:
        t_copy = list(t)
        return t_copy
    else:
        return "Not a list"
y = ""
x = copy_list(y)
print x,"\t", type(y)
y = []
x = copy_list(y)
print x,"\t\t", type(y)
y = None
x = copy_list(y)
print x,"   ", type(y)
y = 10
x = copy_list(y)
print x,"   ", type(y)
y = "abc"
x = copy_list(y)
print x,"   ", type(y)
y = [1,2,3,4]
x = copy_list(y)
print x,"   ", type(y)
y = ["a",2,"b"]
x = copy_list(y)
print x,"   ", type(y)
y = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
x = copy_list(y)
print x,"   ", type(y)     

Results in:

Not a list  <type 'str'>
[]      <type 'list'>
Not a list  <type 'NoneType'>
Not a list  <type 'int'>
Not a list  <type 'str'>
[1, 2, 3, 4]    <type 'list'>
['a', 2, 'b']   <type 'list'>
Not a list  <type 'dict'>
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
0

The try/except block is used for gracefully handling exceptions that are thrown by the interpreter when an unexpected or illegal value is encountered, not for raising exceptions intentionally. For that you want the raise keyword. See this question: How to use "raise" keyword in Python

As a suggestion, your code could look something like this:

def copy_list(t):
    if isinstance(t, list):
        t_copy=[]
        n=len(t)
        i=0
        while i<n:
            t_copy.append(t[i])
            i+=1
        return t_copy
    else:
        raise Exception('Not a list')

Edit: I think you're also going to want the isinstance function, and I have edited the code accordingly. Info on that can be found here.

Community
  • 1
  • 1
McGlothlin
  • 2,059
  • 1
  • 15
  • 28
  • You're welcome! Consider accepting answers when they work for you, and welcome to the site! http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – McGlothlin Oct 27 '15 at 16:25
  • In the interests of fairness, having commented on the other answers, this answer passes the tests with flying colours. – Rolf of Saxony Oct 29 '15 at 06:27