Jordan Rastrick wrote: > Say you're writing, in Python, the extend() method for a Linked List > version of python's builtin list. Its really important to know what > kind of iterable youre being passed in - because if its another > Linked list, and you know it, you can connect the two in 0(1) time; > whereas any other arbitrary iterable is going to take 0(n), as you're > just going to have to append the items one by one. Is this a case > where use of isinstance, to see exactly what kind of Iterable you > have, can be justified? > > def extend(self, elems): > if isinstance(elems, LinkedList): > # Point last to first > else: > for elem in elems: self.append(elem)
Regardless of the various issues surrounding isinstance(), you have a difference in functionality. Since you're just storing a reference in the case of another LinkedList instead of copying it, mutating the LinkedList will be different from mutating another iterable type which has been passed to extend: >>> linkedlist1 = LinkedList() >>> list1 = [1, 2, 3] >>> linkedlist2 = LinkedList([4, 5, 6]) >>> linkedlist1.extend(list1) >>> linkedlist1.extend(linkedlist2) >>> linkedlist1 LinkedList([1, 2, 3, 4, 5, 6]) >>> list1.append(4) >>> linkedlist1 # Notice how there's still only one 4 LinkedList([1, 2, 3, 4, 5, 6]) >>> linkedlist2.append(7) >>> linkedlist1 # Notice how there's now a 7 LinkedList([1, 2, 3, 4, 5, 6, 7]) -- http://mail.python.org/mailman/listinfo/python-list