+ 1
How can I force the function argument to be a list?
def manipulate_data(n): n=list(n) a=[] b=[] for i in n: if i<=0: a.append(i) if i>0: b.append(i) n=[len(a),sum(b)] return n gum= [2,4,5,-6,-7,]print (manipulate_data (gum))
5 odpowiedzi
0
I want the function to be able to test it's argument (n) for only lists allowed
0
First, remove n = list(n) line. You did it to ensure that n is a list, I understand that, but it doesn't solve your problem and actually is purposeless.
What you probably want is to test if n is instance of a list, like this:
if not isinstance(n, list): return None # or raise an exception or something else
However, this is not pythonic way. It's easier to ask forgiveness than permission; assume that you get a list as parameter and fail gracefully if it's not. Wrap your code in try/except construction if you cannot iterate over n. The same goes for comparison with 0: what if n is a list of strings, not integers/floats? Just assume it's good, and fail if you encounter an error.
As a side note, try to not modify your input, it's an unusual side effect, and it's not clear, and it's hard to see through or predict. Use other name than n for your output list construction.
So to conclude, your code would look something like
try:
for i in n:
# do your thing
except TypeError:
print('n is not iterable')
return None
0
thanks trueneu. I really appreciate it man. but I am not still clear on how to restrict implementation to a list of integers only. how do I do that
0
Is this better? is it correct?
def manipulate_data(n):
a=[]
b=[]
if not isinstance(n,list):
raise TypeError
else:
try:
for i in n:
if i<=0:
a.append(i).
if i>0:
b.append(i)
m=[len(a),sum(b)]
return m
except TypeError:
print("your argument is either not iterable! or it isn't a list of integers!")
0
You don't need to check explicitly if an argument is a list if it's in a try/except block.
def manipulate_data(n):
a = []
b = []
try:
try:
for i in n:
if i <= 0:
a.append(i)
if i > 0:
b.append(i)
except TypeError:
print("one of arguments is uncomparable with 0")
return
m = [len(a), sum(b)]
return m
except TypeError:
print("your argument is not iterable.")
This approach will also work if you pass a dict with integer keys, like
print(manipulate_data({1: 'a', 2: 'b'}))
...or anything iterable with numbers as items.
If you really want to explicitly make function fail if n is not a list, get rid of outer try/except block and do an isinstance test and fail if it fails:
def manipulate_data(n):
a = []
b = []
if not isinstance(n, list):
print("argument is not a list")
return
try:
for i in n:
if i <= 0:
a.append(i)
if i > 0:
b.append(i)
except TypeError:
print("one of arguments is uncomparable with 0")
return
m = [len(a), sum(b)]
return m