Pythonic way to check if a function input is a list or string
Question:
I was wondering what the most pythonic way would be to check if a function input is a string or a list. I want the user to be able to enter a list of strings or a string itself.
def example(input):
for string in input:
#Do something here.
print(string)
Obviously this will work in the input is a list of strings but not if the input is a single string. Would the best thing to do here is add type checking in the function itself?
def example(input):
if isinstance(input,list):
for string in input:
print(input)
#do something with strings
else:
print(input)
#do something with the single string
Thanks.
Answers:
Your code is fine. However you mentioned the list should be a list of strings:
if isinstance(some_object, str):
...
elif all(isinstance(item, str) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
...
else:
raise TypeError # or something along that line
Check if input is a list/tuple of strings or a single string
The second approach is fine, except that it should do with print(string_)
and not print(input)
, if it matters:
def example(input):
if isinstance(input,list):
for string_ in input:
print(string_)
#do something with strings
else:
print(input)
#do something with the single string
example(['2','3','4'])
example('HawasKaPujaari')
OUTPUT:
2
3
4
HawasKaPujaari
I was wondering what the most pythonic way would be to check if a function input is a string or a list. I want the user to be able to enter a list of strings or a string itself.
def example(input):
for string in input:
#Do something here.
print(string)
Obviously this will work in the input is a list of strings but not if the input is a single string. Would the best thing to do here is add type checking in the function itself?
def example(input):
if isinstance(input,list):
for string in input:
print(input)
#do something with strings
else:
print(input)
#do something with the single string
Thanks.
Your code is fine. However you mentioned the list should be a list of strings:
if isinstance(some_object, str):
...
elif all(isinstance(item, str) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
...
else:
raise TypeError # or something along that line
Check if input is a list/tuple of strings or a single string
The second approach is fine, except that it should do with print(string_)
and not print(input)
, if it matters:
def example(input):
if isinstance(input,list):
for string_ in input:
print(string_)
#do something with strings
else:
print(input)
#do something with the single string
example(['2','3','4'])
example('HawasKaPujaari')
OUTPUT:
2
3
4
HawasKaPujaari