Richard Rublev
Richard Rublev

Reputation: 8162

Comparing two lists and extracting elements

My code

with open('freq1.txt') as f:
    next(f, None)
    list1 = [line.rstrip() for line in f]

with open('freq2.txt') as f:
    next(f, None)
    list2 = [line.rstrip() for line in f]

print set(list1).intersection(list2)

But I got set([]) For example I have two lists

list1=[1,2,3,4]
list2=[3,2,7,5,9]

I want list with all elements from list1 and list2

newlist=[1,2,3,4,5,7,9]

How to write this?

EDIT I would like to use one way using list comprehensions.

list1=[1.0,2.0,3.1,4.2]
list2=[3.0,2.0,7.2,5.1,9.2]
list3=[2.1,4.2,5.1,9.2]

su1 = list1 + [x for x in list2 if x not in list1]
su2= su1 + [x for x in list3 if x not in su1]
su2=sorted(su2)
print su2list1=[1.0,2.0,3.1,4.2]
list2=[3.0,2.0,7.2,5.1,9.2]
list3=[2.1,4.2,5.1,9.2]

su1 = list1 + [x for x in list2 if x not in list1]
su2= su1 + [x for x in list3 if x not in su1]
su2=sorted(su2)
print su2

Works very nice

[1.0, 2.0, 2.1, 3.0, 3.1, 4.2, 5.1, 7.2, 9.2]

Upvotes: 2

Views: 66

Answers (2)

Garrett R
Garrett R

Reputation: 2662

If you want the elements sorted in ascending order

sorted_unique = sorted(set(list1+list2))

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

You want set.union():

>>> set(list1).union(list2)
set([1, 2, 3, 4, 5, 7, 9])

If you want a list as the result (which is not necessary if you don't want to use the list's attributes like indexing and if you are only dealing with integers because, since the hash of integers is equal to themselves (except -1 which is -2) the set() object will preserve the order as well) you can call the list() function on the result of union().

>>> list(set(list1).union(list2))

Upvotes: 5

Related Questions