Test if a variable is a list or tuple

前端 未结 13 1338
余生分开走
余生分开走 2020-12-22 16:53

In python, what\'s the best way to test if a variable contains a list or a tuple? (ie. a collection)

Is isinstance() as evil as suggested here? http://w

相关标签:
13条回答
  • 2020-12-22 17:15

    In principle, I agree with Ignacio, above, but you can also use type to check if something is a tuple or a list.

    >>> a = (1,)
    >>> type(a)
    (type 'tuple')
    >>> a = [1]
    >>> type(a)
    (type 'list')
    
    0 讨论(0)
  • 2020-12-22 17:16
    if type(x) is list:
        print 'a list'
    elif type(x) is tuple:
        print 'a tuple'
    else:
        print 'neither a tuple or a list'
    
    0 讨论(0)
  • 2020-12-22 17:18

    Has to be more complex test if you really want to handle just about anything as function argument.

    type(a) != type('') and hasattr(a, "__iter__")
    

    Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('').

    Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.

    0 讨论(0)
  • 2020-12-22 17:19

    On Python 2.8 type(list) is list returns false
    I would suggest comparing the type in this horrible way:

    if type(a) == type([]) :
      print "variable a is a list"
    

    (well at least on my system, using anaconda on Mac OS X Yosemite)

    0 讨论(0)
  • 2020-12-22 17:20

    Not the most elegant, but I do (for Python 3):

    if hasattr(instance, '__iter__') and not isinstance(instance, (str, bytes)):
        ...
    

    This allows other iterables (like Django querysets) but excludes strings and bytestrings. I typically use this in functions that accept either a single object ID or a list of object IDs. Sometimes the object IDs can be strings and I don't want to iterate over those character by character. :)

    0 讨论(0)
  • 2020-12-22 17:22

    Python uses "Duck typing", i.e. if a variable kwaks like a duck, it must be a duck. In your case, you probably want it to be iterable, or you want to access the item at a certain index. You should just do this: i.e. use the object in for var: or var[idx] inside a try block, and if you get an exception it wasn't a duck...

    0 讨论(0)
提交回复
热议问题