Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9119397
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T05:23:12+00:00 2026-06-17T05:23:12+00:00

I have two lists, let’s say: keys1 = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘H’,

  • 0

I have two lists, let’s say:

keys1 = ['A', 'B', 'C', 'D', 'E',           'H', 'I']
keys2 = ['A', 'B',           'E', 'F', 'G', 'H',      'J', 'K']

How do I create a merged list without duplicates that preserve the order of both lists, inserting the missing elements where they belong? Like so:

merged = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

Note that the elements can be compared against equality but not ordered (they are complex strings).
The elements can’t be ordered by comparing them, but they have an order based on their occurrence in the original lists.

In case of contradiction (different order in both input lists), any output containing all elements is valid. Of course with bonus points if the solution shows ‘common sense’ in preserving most of the order.

Again (as some comments still argue about it), the lists normally don’t contradict each other in terms of the order of the common elements. In case they do, the algorithm needs to handle that error gracefully.

I started with a version that iterates over the lists with .next() to advance just the list containing the unmatched elements, but .next() just doesn’t know when to stop.

merged = []
L = iter(keys1)
H = iter(keys2)
l = L.next()
h = H.next()

for i in range(max(len(keys1, keys2))):
  if l == h:
    if l not in merged:
      merged.append(l)
    l = L.next()
    h = H.next()

  elif l not in keys2:
    if l not in merged:
      merged.append(l)
    l = L.next()

  elif h not in keys1:
    if h not in merged:
      merged.append(h)
    h = H.next()

  else: # just in case the input is badly ordered
    if l not in merged:
      merged.append(l)
    l = L.next()
    if h not in merged:
      merged.append(h)
    h = H.next()   

print merged

This obviously doesn’t work, as .next() will cause an exception for the shortest list. Now I could update my code to catch that exception every time I call .next(). But the code already is quite un-pythonic and this would clearly burst the bubble.

Does anyone have a better idea of how to iterate over those lists to combine the elements?

Bonus points if I can do it for three lists in one go.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T05:23:13+00:00Added an answer on June 17, 2026 at 5:23 am

    What you need is basically what any merge utility does: It tries to merge two sequences, while keeping the relative order of each sequence. You can use Python’s difflib module to diff the two sequences, and merge them:

    from difflib import SequenceMatcher
    
    def merge_sequences(seq1,seq2):
        sm=SequenceMatcher(a=seq1,b=seq2)
        res = []
        for (op, start1, end1, start2, end2) in sm.get_opcodes():
            if op == 'equal' or op=='delete':
                #This range appears in both sequences, or only in the first one.
                res += seq1[start1:end1]
            elif op == 'insert':
                #This range appears in only the second sequence.
                res += seq2[start2:end2]
            elif op == 'replace':
                #There are different ranges in each sequence - add both.
                res += seq1[start1:end1]
                res += seq2[start2:end2]
        return res
    

    Example:

    >>> keys1 = ['A', 'B', 'C', 'D', 'E',           'H', 'I']
    >>> keys2 = ['A', 'B',           'E', 'F', 'G', 'H',      'J', 'K']
    >>> merge_sequences(keys1, keys2)
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
    

    Note that the answer you expect is not necessarily the only possible one. For example, if we change the order of sequences here, we get another answer which is just as valid:

    >>> merge_sequences(keys2, keys1)
    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'I']
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have a list of dicts. I define duplicates as any two
let's say I have two lists: a = list(1,2,3) b = list(4,5,6) So I
Let's say I have a list somewhere called majorPowers which contain these two lists:
I have two generic lists. Let's say they are List< A > and List<
Let's say that I have got two lists: temp<-c(con.sin.results,sin.results,exp.results) Temp<-c([,1:16],[,17:32],[,33:48],[,49:64]) Each of the variables
We have two lists: a=['1','2','3','4'] b=['2','3','4','5'] How to get a list with elements that
I have two lists, let's say: a = [1,2,3] b = [1,2,3,1,2,3] I would
Let's say you have two lists, L1 and L2, of the same length, N.
Let's say I have two generic lists of the same type. How do I
I have two lists that i need to combine where the second list has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.