Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take two lists and combine them excluding any duplicates?

Tags:

python

I'd like to make one list from two separate lists of unique items.

There are other similar questions but there didn't seem to be any that concerned doing this problem effectively since the lists are a few million items long.

Totally unrelated: am I the only one who hates how the tags suggestion box covers up the "post your question" button?

like image 358
funk-shun Avatar asked Jan 12 '11 21:01

funk-shun


People also ask

How do I combine two lists without duplicates?

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.

How do you avoid duplicates in lists?

If you don't want duplicates, use a Set instead of a List . To convert a List to a Set you can use the following code: // list is some List of Strings Set<String> s = new HashSet<String>(list); If really necessary you can use the same construction to convert a Set back into a List .

How do you collate a list in Excel?

On the Data tab, under Tools, click Consolidate. In the Function box, click the function that you want Excel to use to consolidate the data. In each source sheet, select your data, and then click Add. The file path is entered in All references.


4 Answers

Use a set.

>>> first = [1, 2, 3, 4]
>>> second = [3, 2, 5, 6, 7]
>>> third = list(set(first) | set(second))      # '|' is union
>>> third
[1, 2, 3, 4, 5, 6, 7]
like image 84
user225312 Avatar answered Oct 01 '22 01:10

user225312


A slightly more efficient way to do it:

>>> first = [1, 2, 3, 4]
>>> second = [3, 2, 5, 6, 7]

# New way
>>> list(set(first + second))
[1, 2, 3, 4, 5, 6, 7]
#1000000 loops, best of 3: 1.42 µs per loop

# Old way
>>> list(set(first) | set(second))
[1, 2, 3, 4, 5, 6, 7]
#1000000 loops, best of 3: 1.83 µs per loop

The new way is more efficient because it has only one set() instead of 2.

like image 36
Benjamin Devienne Avatar answered Sep 30 '22 23:09

Benjamin Devienne


>>> l1 = range(10)
>>> l2 = range(5, 15)
>>> set(l1) | set(l2)
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
like image 44
virhilo Avatar answered Oct 01 '22 01:10

virhilo


If someone want to do it without set():

a = [1,2,3]
b = [2,3,4]
newlist=[]
for i in a:
    newlist.append(i)
for z in b:
    if z not in newlist:
        newlist.append(z)
newlist.sort()
print newlist
like image 35
Prashant Lakhera Avatar answered Sep 30 '22 23:09

Prashant Lakhera