-1

I have one list that in a specific order let's say something like ['hello', 'I', 'like', 'sunshine'] and I have a second list that contains all of the first list and some extra elements ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']. This is sort of a nonsensical example, but essentially the main idea is the first list is a subset of the second, but the elements from the first do not appear in the same order that they originally appeared in (they are scrambled up in the second list). I want to reorder the second list so it has the elements from the first list in the beginning in the original order, and then has its unique elements. Therefore, this reordered second list would like ['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows'].

Hopefully this makes sense. I actually don't care how the unique elements appear in the final reordered list (they can be rearranged for all I care but it is crucial the elements from the first list appear in the beginning and maintain original order). How do I achieve this? I am a bit lost.

martineau
  • 119,623
  • 25
  • 170
  • 301
Jane Sully
  • 3,137
  • 10
  • 48
  • 87
  • Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic), [how to ask](http://stackoverflow.com/help/how-to-ask), and [... the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is not a design, coding, research, or tutorial resource. However, if you follow whatever resources you find on line, make an honest coding attempt, and run into a problem, you'd have a good example to post. – Prune Feb 15 '19 at 17:59
  • See e.g. https://stackoverflow.com/a/51903823/3001761 – jonrsharpe Feb 15 '19 at 18:00

2 Answers2

1

You can take List1, and append every item from List2 not in List1 to List1 .

l1 = ['hello', 'I', 'like', 'sunshine']
l2 = ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']

new_list = l1.copy()

for item in l2:
    if item not in l1:
        new_list.append(item)

print(new_list)

Out:

['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']
max
  • 4,141
  • 5
  • 26
  • 55
  • This is modifying the first list, which might not be intended as per the OP's question. He/She explicitly says he/she wants to *mutate* the *second* list. – Matias Cicero Feb 15 '19 at 18:10
1

Here's a nice one-liner solution:

a = ['hello', 'I', 'like', 'sunshine']
b = ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']

b = sorted(b, key=lambda x: a.index(x) if x in a else len(a) + b.index(x))
# b = ['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154