Merge two linked lists in Python I have a method which will merger two sorted list together. The function works, but I saw some duplicated code. 

Any ideas to make the code more elegant?

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

def MergeLists(headA, headB):
    head = tail = Node('',None)
    while headA or headB:

        # duplicated code here
        if headA is not None:
            if (headB and headA.data&lt;=headB.data) or (headB is None):
                tail.next = headA
                tail = headA
                headA = headA.next

        if headB is not None:
            if (headA and headB.data &lt;= headA.data) or (headA is None):
                tail.next = headB
                tail = headB
                headB = headB.next

    return head.next
Elegance is in the eye of the beholder; the following (replacing the duplicated code here part) is certainly less redundant:

for i in xrange(2):
    if headA is not None:
        if ( headB and headA.data&lt;=headB.data) or (headB is None):
            tail.next = headA
            tail = headA
            headA = headA.next
    # When i==0, this will flip headA &amp; headB
    # When i==1, it will restore them
    headA,headB = headB,headA