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.

Asked By: Cr1064

||

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

Answered By: ALFA

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
Answered By: DirtyBit
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.