How can I tell if a python variable is a string or a list? How can I tell if a python variable is a string or a list? python python

How can I tell if a python variable is a string or a list?


isinstance(your_var, basestring)


Well, there's nothing unpythonic about checking type. Having said that, if you're willing to put a small burden on the caller:

def func( *files ):    for f in files:         doSomethingWithFile( f )func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3')func( 'file1' )

I'd argue this is more pythonic in that "explicit is better than implicit". Here there is at least a recognition on the part of the caller when the input is already in list form.


Personally, I don't really like this sort of behavior -- it interferes with duck typing. One could argue that it doesn't obey the "Explicit is better than implicit" mantra. Why not use the varargs syntax:

def func( *files ):    for f in files:        doSomethingWithFile( f )func( 'file1', 'file2', 'file3' )func( 'file1' )func( *listOfFiles )