-1

I have two lists in Python:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

I want to merge them into a single list such that:

  1. No duplicates remain
  2. The original order of elements is preserved

For the example above, the desired output is: [1, 2, 3, 4, 5, 6].

I tried using list(set(list1 + list2)) but it doesn't preserve the order. How can I achieve this efficiently in Python?

1
  • How is that possible when the lists are for example [1,2] and [2,1]? However you "merge" them, the result will have a different order than one of the lists. Commented Oct 14 at 11:47

1 Answer 1

2

You can try dict.fromkeys()

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

merged = list(dict.fromkeys(list1 + list2))
print(merged) 


output

[1, 2, 3, 4, 5, 6]
Sign up to request clarification or add additional context in comments.

1 Comment

l1 = [1,2,3,4] l2 = [3,4,5,6] l1.extend(l2) new = list(set(l1)) print(new)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.