What is the Pythonic Way of Differentiating Between a String and a List? What is the Pythonic Way of Differentiating Between a String and a List? python python

What is the Pythonic Way of Differentiating Between a String and a List?


No need to import modules, isinstance(), str and unicode (versions before 3 -- there's no unicode in 3!) will do the job for you.

Python 2.x:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> isinstance(u'', (str, unicode))True>>> isinstance('', (str, unicode))True>>> isinstance([], (str, unicode))False>>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']):...     print type(value)... <type 'str'><type 'unicode'><type 'list'>

Python 3.x:

Python 3.2 (r32:88445, May 29 2011, 08:00:24) [GCC 4.2.1 (Apple Inc. build 5664)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> isinstance('☃ ', str)True>>> isinstance([], str)False>>> for value in ('snowman', '☃ ', ['snowman', '☃ ']):...     print(type(value))... <class 'str'><class 'str'><class 'list'>

From PEP008:

Object type comparisons should always use isinstance() instead of comparing types directly.


Since Python3 no longer has unicode or basestring, in this case ( where you are expecting either a list or a string) it's better to test against list

if isinstance(thing, list):    # treat as listelse:    # treat as str/unicode

as that is compatible with both Python2 and Python3


Another method, using the practice of "It's better to ask forgiveness than permission," duck-typing being generally preferred in Python, you could try to do what you want first, e.g.:

try:    value = v.split(',')[0]except AttributeError:  # 'list' objects have no split() method    value = v[0]