List match

Paddy paddy3118 at netscape.net
Thu Aug 17 17:44:01 EDT 2006


OriginalBrownster wrote:
> Hi there:
>
> I know this probably is a very easy thing to do in python, but i wanted
> to compare 2 lists and generate a new list that does not copy similar
> entries. An example below
>
> list= ["apple", "banana", "grape"]
> list2=["orange","banana", "pear"]
>
> now I want to compare these lits and generate a third list after
> comparison
>
> list3 would be ["apple", "banana","grape","orange", "pear"]
>
> hence the double entry would not show up?
>
> Is there a way to do this??
>
> Stephen

This solution uses sets; removes all duplicates and is order
preserving.
Remove the outer sorted wrapper if the order need not be preserved.

>>> lst= ["apple", "banana", "grape"]
>>> lst2=["orange","banana", "pear"]
>>> lst3= lst+lst2
>>> sorted([x for x in set(lst3)], key = lambda x: lst3.index(x))
['apple', 'banana', 'grape', 'orange', 'pear']
>>> 

- Paddy




More information about the Python-list mailing list