Common elements comparison between 2 lists
def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
"""
for element in list1:
if element in list2:
return list(element)
Got that so far, but can't seem to get it to work!
Any ideas?
python list
add a comment |
def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
"""
for element in list1:
if element in list2:
return list(element)
Got that so far, but can't seem to get it to work!
Any ideas?
python list
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12
add a comment |
def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
"""
for element in list1:
if element in list2:
return list(element)
Got that so far, but can't seem to get it to work!
Any ideas?
python list
def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
"""
for element in list1:
if element in list2:
return list(element)
Got that so far, but can't seem to get it to work!
Any ideas?
python list
python list
edited Sep 11 at 6:17
Alex.K.
2,13192834
2,13192834
asked May 19 '10 at 10:57
Daniel
384154
384154
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12
add a comment |
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12
add a comment |
16 Answers
16
active
oldest
votes
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
1
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
11
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
|
show 1 more comment
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
add a comment |
The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result
list and collecting the common elements in that list:
def common_elements(list1, list2):
result =
for element in list1:
if element in list2:
result.append(element)
return result
An even shorter version using list comprehensions:
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.
1
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
add a comment |
use set intersections, set(list1) & set(list2)
>>> def common_elements(list1, list2):
... return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>
Note that result list could be different order with original list.
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
3
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
add a comment |
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions useset
which is not stable (aka the order is lost).
– lifebalance
Jun 15 '17 at 14:14
add a comment |
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
VERY slow...
– xtluo
Nov 14 at 7:52
add a comment |
1) Method1
saving list1 is dictionary and then iterating each elem in list2
def findarrayhash(a,b):
h1={k:1 for k in a}
for val in b:
if val in h1:
print("common found",val)
del h1[val]
else:
print("different found",val)
for key in h1.iterkeys():
print ("different found",key)
Finding Common and Different elements:
2) Method2
using set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
add a comment |
Hi, this is my propose (very simple)
import random
i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i:
if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
print(x) # print out the results
add a comment |
Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.
The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't give the correct number of elements when the input order matters.
#finds common elements
def common(list1, list2):
result =
intersect = list(set(list1).intersection(list2))
#using the intersection, find the min
count1 = 0
count2 = 0
for i in intersect:
for j in list1:
if i == j:
count1 += 1
for k in list2:
if i == k:
count2 += 1
minCount = min(count2,count1)
count1 = 0
count2 = 0
#append common factor that many times
for j in range(minCount):
result.append(i)
return result
add a comment |
f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=
for i in f_list:
# checking if each element of first list exists in second list
if i in s_list:
#if so add it in common elements list
common_elements.append(i)
print(common_elements)
add a comment |
a_list = range(1,10)
b_list = range(5, 25)
both =
for i in b_list:
for j in a_list:
if i == j:
both.append(i)
2
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
1
This is going to be so slow, it's better to use generated list such as[i for i in x if i in y]
.
– maf88_
May 14 at 21:20
add a comment |
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
add a comment |
list_1=range(0,100)
list_2=range(0,100,5)
final_list=
for i in list_1:
for j in list_2:
if i==j:
final_list.append(i)
print(set(final_list))
1
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
add a comment |
this is my proposition
i think its easier with sets than with a for loop
def unique_common_items(list1, list2):
"""Produce the set of *unique* common items in two lists.
return list(set(list1) & set(list2))
add a comment |
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
add a comment |
Your problem is that you're returning from inside the for loop so you'll only get the first match. The solution is to move your return outside the loop.
def elementosEnComunEntre(lista1,lista2):
elementosEnComun = set()
for e1 in lista1:
if(e1 in lista2):
elementosEnComun.add(e1)
return list(elementosEnComun)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2864842%2fcommon-elements-comparison-between-2-lists%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
16 Answers
16
active
oldest
votes
16 Answers
16
active
oldest
votes
active
oldest
votes
active
oldest
votes
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
1
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
11
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
|
show 1 more comment
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
1
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
11
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
|
show 1 more comment
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
answered May 19 '10 at 11:00
SilentGhost
190k46263262
190k46263262
1
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
11
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
|
show 1 more comment
1
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
11
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
1
1
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
+1 but personally I'd used frozenset as it's immutable and so can be used as dictionary key etc
– zebrabox
May 19 '10 at 11:04
11
11
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
This will return the /unique/ common elements, but not any repeated elements that may exist.
– Dologan
Mar 20 '14 at 18:52
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@SilentGhost. How to get the number of matched elements from two list. In this case it is 2.
– Poka
Dec 9 '17 at 11:53
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@Poka len(list(set(list1).intersection(list2)))
– Dharmanshu Kamra
Jan 4 at 1:38
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
@zebrabox can you show us the example?
– Md. Alamin Mahamud
Aug 13 at 10:56
|
show 1 more comment
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
add a comment |
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
add a comment |
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
answered Jul 22 '16 at 23:17
BeyondRubicon
34132
34132
add a comment |
add a comment |
The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result
list and collecting the common elements in that list:
def common_elements(list1, list2):
result =
for element in list1:
if element in list2:
result.append(element)
return result
An even shorter version using list comprehensions:
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.
1
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
add a comment |
The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result
list and collecting the common elements in that list:
def common_elements(list1, list2):
result =
for element in list1:
if element in list2:
result.append(element)
return result
An even shorter version using list comprehensions:
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.
1
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
add a comment |
The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result
list and collecting the common elements in that list:
def common_elements(list1, list2):
result =
for element in list1:
if element in list2:
result.append(element)
return result
An even shorter version using list comprehensions:
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.
The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result
list and collecting the common elements in that list:
def common_elements(list1, list2):
result =
for element in list1:
if element in list2:
result.append(element)
return result
An even shorter version using list comprehensions:
def common_elements(list1, list2):
return [element for element in list1 if element in list2]
However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.
edited May 23 '17 at 10:31
Community♦
11
11
answered May 19 '10 at 11:30
Tamás
37.6k881108
37.6k881108
1
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
add a comment |
1
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
1
1
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
Great for both proposals
– dlewin
Sep 21 '15 at 12:41
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
NOTE: The above methods will only work for equal sized lists. If you are working with unequal sized lists, as I am, then you will need to evaluate the order based on len() prior to calling the function: list1 = [2,2,2], list2[2,3] -> [2,2,2] list1 = [2,3], list2[2,2,2] -> [2]
– redthumb
Sep 30 '16 at 11:56
add a comment |
use set intersections, set(list1) & set(list2)
>>> def common_elements(list1, list2):
... return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>
Note that result list could be different order with original list.
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
3
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
add a comment |
use set intersections, set(list1) & set(list2)
>>> def common_elements(list1, list2):
... return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>
Note that result list could be different order with original list.
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
3
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
add a comment |
use set intersections, set(list1) & set(list2)
>>> def common_elements(list1, list2):
... return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>
Note that result list could be different order with original list.
use set intersections, set(list1) & set(list2)
>>> def common_elements(list1, list2):
... return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>
Note that result list could be different order with original list.
answered May 19 '10 at 11:00
YOU
83.9k20151199
83.9k20151199
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
3
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
add a comment |
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
3
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thanks for the help. Understand where I went wrong and what to work on next time. :)
– Daniel
May 19 '10 at 12:29
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
Thats great, Daniel :-)
– YOU
May 19 '10 at 12:47
3
3
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
great solution. is there also a way to preserve the order with this?
– tarrasch
Aug 30 '12 at 15:47
add a comment |
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions useset
which is not stable (aka the order is lost).
– lifebalance
Jun 15 '17 at 14:14
add a comment |
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions useset
which is not stable (aka the order is lost).
– lifebalance
Jun 15 '17 at 14:14
add a comment |
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
edited Mar 20 '14 at 18:55
answered Mar 20 '14 at 18:49
Dologan
2,4282426
2,4282426
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions useset
which is not stable (aka the order is lost).
– lifebalance
Jun 15 '17 at 14:14
add a comment |
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions useset
which is not stable (aka the order is lost).
– lifebalance
Jun 15 '17 at 14:14
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
Awesome solution, seems the most thorough, if a bit terse
– Hendeca
Mar 8 '17 at 21:25
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions use
set
which is not stable (aka the order is lost).– lifebalance
Jun 15 '17 at 14:14
This should be the answer that should have been selected! I am assuming it also works for unequal lists. Also most of the solutions use
set
which is not stable (aka the order is lost).– lifebalance
Jun 15 '17 at 14:14
add a comment |
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
VERY slow...
– xtluo
Nov 14 at 7:52
add a comment |
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
VERY slow...
– xtluo
Nov 14 at 7:52
add a comment |
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
answered Mar 28 at 19:13
Mahdi Ghelichi
206311
206311
VERY slow...
– xtluo
Nov 14 at 7:52
add a comment |
VERY slow...
– xtluo
Nov 14 at 7:52
VERY slow...
– xtluo
Nov 14 at 7:52
VERY slow...
– xtluo
Nov 14 at 7:52
add a comment |
1) Method1
saving list1 is dictionary and then iterating each elem in list2
def findarrayhash(a,b):
h1={k:1 for k in a}
for val in b:
if val in h1:
print("common found",val)
del h1[val]
else:
print("different found",val)
for key in h1.iterkeys():
print ("different found",key)
Finding Common and Different elements:
2) Method2
using set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
add a comment |
1) Method1
saving list1 is dictionary and then iterating each elem in list2
def findarrayhash(a,b):
h1={k:1 for k in a}
for val in b:
if val in h1:
print("common found",val)
del h1[val]
else:
print("different found",val)
for key in h1.iterkeys():
print ("different found",key)
Finding Common and Different elements:
2) Method2
using set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
add a comment |
1) Method1
saving list1 is dictionary and then iterating each elem in list2
def findarrayhash(a,b):
h1={k:1 for k in a}
for val in b:
if val in h1:
print("common found",val)
del h1[val]
else:
print("different found",val)
for key in h1.iterkeys():
print ("different found",key)
Finding Common and Different elements:
2) Method2
using set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
1) Method1
saving list1 is dictionary and then iterating each elem in list2
def findarrayhash(a,b):
h1={k:1 for k in a}
for val in b:
if val in h1:
print("common found",val)
del h1[val]
else:
print("different found",val)
for key in h1.iterkeys():
print ("different found",key)
Finding Common and Different elements:
2) Method2
using set
def findarrayset(a,b):
common = set(a)&set(b)
diff=set(a)^set(b)
print list(common)
print list(diff)
edited Jul 22 at 22:33
kichik
19k25778
19k25778
answered Aug 12 '15 at 20:57
J.S
6117
6117
add a comment |
add a comment |
Hi, this is my propose (very simple)
import random
i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i:
if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
print(x) # print out the results
add a comment |
Hi, this is my propose (very simple)
import random
i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i:
if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
print(x) # print out the results
add a comment |
Hi, this is my propose (very simple)
import random
i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i:
if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
print(x) # print out the results
Hi, this is my propose (very simple)
import random
i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i:
if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
print(x) # print out the results
answered Jul 22 at 22:27
Artur Ludwik
113
113
add a comment |
add a comment |
Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.
The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't give the correct number of elements when the input order matters.
#finds common elements
def common(list1, list2):
result =
intersect = list(set(list1).intersection(list2))
#using the intersection, find the min
count1 = 0
count2 = 0
for i in intersect:
for j in list1:
if i == j:
count1 += 1
for k in list2:
if i == k:
count2 += 1
minCount = min(count2,count1)
count1 = 0
count2 = 0
#append common factor that many times
for j in range(minCount):
result.append(i)
return result
add a comment |
Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.
The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't give the correct number of elements when the input order matters.
#finds common elements
def common(list1, list2):
result =
intersect = list(set(list1).intersection(list2))
#using the intersection, find the min
count1 = 0
count2 = 0
for i in intersect:
for j in list1:
if i == j:
count1 += 1
for k in list2:
if i == k:
count2 += 1
minCount = min(count2,count1)
count1 = 0
count2 = 0
#append common factor that many times
for j in range(minCount):
result.append(i)
return result
add a comment |
Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.
The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't give the correct number of elements when the input order matters.
#finds common elements
def common(list1, list2):
result =
intersect = list(set(list1).intersection(list2))
#using the intersection, find the min
count1 = 0
count2 = 0
for i in intersect:
for j in list1:
if i == j:
count1 += 1
for k in list2:
if i == k:
count2 += 1
minCount = min(count2,count1)
count1 = 0
count2 = 0
#append common factor that many times
for j in range(minCount):
result.append(i)
return result
Here's a rather brute force method that I came up with. It's certainly not the most efficient but it's something.
The problem I found with some of the solutions here is that either it doesn't give repeated elements or it doesn't give the correct number of elements when the input order matters.
#finds common elements
def common(list1, list2):
result =
intersect = list(set(list1).intersection(list2))
#using the intersection, find the min
count1 = 0
count2 = 0
for i in intersect:
for j in list1:
if i == j:
count1 += 1
for k in list2:
if i == k:
count2 += 1
minCount = min(count2,count1)
count1 = 0
count2 = 0
#append common factor that many times
for j in range(minCount):
result.append(i)
return result
answered Jan 27 '16 at 16:39
paperhawk
13
13
add a comment |
add a comment |
f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=
for i in f_list:
# checking if each element of first list exists in second list
if i in s_list:
#if so add it in common elements list
common_elements.append(i)
print(common_elements)
add a comment |
f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=
for i in f_list:
# checking if each element of first list exists in second list
if i in s_list:
#if so add it in common elements list
common_elements.append(i)
print(common_elements)
add a comment |
f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=
for i in f_list:
# checking if each element of first list exists in second list
if i in s_list:
#if so add it in common elements list
common_elements.append(i)
print(common_elements)
f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=
for i in f_list:
# checking if each element of first list exists in second list
if i in s_list:
#if so add it in common elements list
common_elements.append(i)
print(common_elements)
edited May 14 at 17:46
maf88_
7111
7111
answered Apr 18 at 6:12
Siva Kumar
5714
5714
add a comment |
add a comment |
a_list = range(1,10)
b_list = range(5, 25)
both =
for i in b_list:
for j in a_list:
if i == j:
both.append(i)
2
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
1
This is going to be so slow, it's better to use generated list such as[i for i in x if i in y]
.
– maf88_
May 14 at 21:20
add a comment |
a_list = range(1,10)
b_list = range(5, 25)
both =
for i in b_list:
for j in a_list:
if i == j:
both.append(i)
2
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
1
This is going to be so slow, it's better to use generated list such as[i for i in x if i in y]
.
– maf88_
May 14 at 21:20
add a comment |
a_list = range(1,10)
b_list = range(5, 25)
both =
for i in b_list:
for j in a_list:
if i == j:
both.append(i)
a_list = range(1,10)
b_list = range(5, 25)
both =
for i in b_list:
for j in a_list:
if i == j:
both.append(i)
edited May 15 at 0:02
maf88_
7111
7111
answered Apr 4 at 17:34
kamran kausar
34144
34144
2
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
1
This is going to be so slow, it's better to use generated list such as[i for i in x if i in y]
.
– maf88_
May 14 at 21:20
add a comment |
2
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
1
This is going to be so slow, it's better to use generated list such as[i for i in x if i in y]
.
– maf88_
May 14 at 21:20
2
2
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
Please add some comments with your answers.
– cosmoonot
Apr 4 at 18:00
1
1
This is going to be so slow, it's better to use generated list such as
[i for i in x if i in y]
.– maf88_
May 14 at 21:20
This is going to be so slow, it's better to use generated list such as
[i for i in x if i in y]
.– maf88_
May 14 at 21:20
add a comment |
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
add a comment |
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
add a comment |
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
answered Sep 9 at 13:10
Sai Saagar Sharman
317
317
add a comment |
add a comment |
list_1=range(0,100)
list_2=range(0,100,5)
final_list=
for i in list_1:
for j in list_2:
if i==j:
final_list.append(i)
print(set(final_list))
1
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
add a comment |
list_1=range(0,100)
list_2=range(0,100,5)
final_list=
for i in list_1:
for j in list_2:
if i==j:
final_list.append(i)
print(set(final_list))
1
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
add a comment |
list_1=range(0,100)
list_2=range(0,100,5)
final_list=
for i in list_1:
for j in list_2:
if i==j:
final_list.append(i)
print(set(final_list))
list_1=range(0,100)
list_2=range(0,100,5)
final_list=
for i in list_1:
for j in list_2:
if i==j:
final_list.append(i)
print(set(final_list))
edited Sep 15 at 9:02
answered Sep 15 at 8:49
Kotha siddu
11
11
1
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
add a comment |
1
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
1
1
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
#{0, 65, 35, 5, 70, 40, 10, 75, 45, 15, 80, 50, 20, 85, 55, 25, 90, 60, 30, 95} " Converted to set to remove duplicates"
– Kotha siddu
Sep 15 at 9:03
add a comment |
this is my proposition
i think its easier with sets than with a for loop
def unique_common_items(list1, list2):
"""Produce the set of *unique* common items in two lists.
return list(set(list1) & set(list2))
add a comment |
this is my proposition
i think its easier with sets than with a for loop
def unique_common_items(list1, list2):
"""Produce the set of *unique* common items in two lists.
return list(set(list1) & set(list2))
add a comment |
this is my proposition
i think its easier with sets than with a for loop
def unique_common_items(list1, list2):
"""Produce the set of *unique* common items in two lists.
return list(set(list1) & set(list2))
this is my proposition
i think its easier with sets than with a for loop
def unique_common_items(list1, list2):
"""Produce the set of *unique* common items in two lists.
return list(set(list1) & set(list2))
answered Oct 16 at 9:49
Elasri
9618
9618
add a comment |
add a comment |
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
add a comment |
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
add a comment |
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
answered Nov 25 at 19:08
nEO
1,60911319
1,60911319
add a comment |
add a comment |
Your problem is that you're returning from inside the for loop so you'll only get the first match. The solution is to move your return outside the loop.
def elementosEnComunEntre(lista1,lista2):
elementosEnComun = set()
for e1 in lista1:
if(e1 in lista2):
elementosEnComun.add(e1)
return list(elementosEnComun)
add a comment |
Your problem is that you're returning from inside the for loop so you'll only get the first match. The solution is to move your return outside the loop.
def elementosEnComunEntre(lista1,lista2):
elementosEnComun = set()
for e1 in lista1:
if(e1 in lista2):
elementosEnComun.add(e1)
return list(elementosEnComun)
add a comment |
Your problem is that you're returning from inside the for loop so you'll only get the first match. The solution is to move your return outside the loop.
def elementosEnComunEntre(lista1,lista2):
elementosEnComun = set()
for e1 in lista1:
if(e1 in lista2):
elementosEnComun.add(e1)
return list(elementosEnComun)
Your problem is that you're returning from inside the for loop so you'll only get the first match. The solution is to move your return outside the loop.
def elementosEnComunEntre(lista1,lista2):
elementosEnComun = set()
for e1 in lista1:
if(e1 in lista2):
elementosEnComun.add(e1)
return list(elementosEnComun)
edited Nov 29 at 21:02
Woody1193
2,246930
2,246930
answered Nov 29 at 20:17
Ignacio Alvarez
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2864842%2fcommon-elements-comparison-between-2-lists%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Hi, could you add some details on how you plan to use the code? If this is to complete an assignment, it may be better to choose a solution which encapsulates the "Pythonic" way. However, if efficiency is your concern, then the "Pythonic" way is unlikely to be the most efficient solution. Advising us on these details will help solutions aim to solve your problem.
– Matthew Cliatt
May 15 at 2:12