-2
  1. isinstance(list(), type(mylist))

  2. isinstance(mylist, list)

Is there any difference apart from the speed? I can see 2 is faster.

user2715898
  • 921
  • 3
  • 13
  • 20

2 Answers2

3

If used correctly, the results will be the same. But you should only use the second version.

There's no need to create an empty object, i.e. list(), and no reason for an extra function call via type.

There's also a danger you'll do something like this:

from collections import OrderedDict

array = dict()

res1 = isinstance(OrderedDict(), type(array))  # True
res2 = isinstance(array, OrderedDict)          # False
jpp
  • 159,742
  • 34
  • 281
  • 339
  • This is a good point, the results are not always symmetric because of subclasses, of course we don't what they actually want in this case – Chris_Rands Nov 19 '18 at 15:20
  • @Chris_Rands, Yup, it's just an illustration of *what's more likely* to go wrong with the first method. – jpp Nov 19 '18 at 15:21
1

The first one is very inefficient, as you are first creating a new list object, and then identifying the type of my_list and then checking if they both are same.

The second option is how the isinstance function is supposed to be used.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69