2

I'm trying to check if the list have something in common. If they have one print "x" but if they don't print "y". But only one of them, not both. Code:

lista_1 = [1, 2, 4, 5, 6, 7, 8]
lista_2 = [10, 12, 16, 5, 3, 2]
for i in lista_1:
    if i in lista_2:
        print ('Tienen un elemento en común')
        break
        exit()
    if i not in lista_2:
        print ('No tienen ningún elemento en común')

With this way it prints x once and y once, but I want to print only one of them

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124

6 Answers6

6

You need to iterate through the whole list before you can say that they have no elements in common, so I added a for-else statement. Additionally, I made lista_2 a set to increase efficiency.

lista_1 = [1, 2, 4, 5, 6, 7, 8]
set_2 = {10, 12, 16, 5, 3, 2}
for i in lista_1:
    if i in set_2:
        print('Tienen un elemento en común')
        break
else:
    print('No tienen ningún elemento en común')
Neil
  • 14,063
  • 3
  • 30
  • 51
0

The easiest way to check if 2 lists have common elements is to check intersection between the two:

common = list(set(lista_1).intersection(lista_2))
if(now common):
    print("no common elements")
Gal Dreiman
  • 3,969
  • 2
  • 21
  • 40
0

An easier approach would be to use:

(list(set(lista_1) & set(lista_2)))

This will take both lists, convert them to unordered sets that can then be compared between one another with the & (and) operator. The result of this will be a set containing the items that match in both sets, which the outermost list() method will convert back into a list.

And if it's not empty, you've got matches. ;)

0

You could do by looking at the intersection of the two corresponding sets:

 if set(lista_1) & set(lista_2):
    print('common elemens')
 else:
    print("no common elements")
greole
  • 4,523
  • 5
  • 29
  • 49
0

To make the process faster and more concise, you could use a set (conjunto in Spanish, I believe) for fast lookup, and use any() to stop at the first found common element :

#encoding: utf-8

lista_1 = [1, 2, 4, 5, 6, 7, 8]
lista_2 = [10, 12, 16, 5, 3, 2]

conjunto_2 = set(lista_2)

comun = any(elemento_1 in conjunto_2 for elemento_1 in lista_1)

if comun:
    print('Tienen un elemento en común')
else:
    print ('No tienen ningún elemento en común')
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
-1

If you code 2 ifs, it will show both. You must use 1 if and 1 elif. Change the second if to elif or else.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Amir
  • 1