How to check the common elements between two lists in python

advertisements

I am having a bit of trouble when I try and check for overlapping elements in list.

This means that I will have to check for common elements between two lists.

The way in which my programme works is that the player enters their two end coordinates for a certain ship, it then creates a list out of this of all of the ships coordinates (ie if they enter (1,1) and (1,5), it would create [(1,1),(1,2),(1,3),(1,4),(1,5)]

I have also tried using the following code but it doesn't work for the way I want it to:

ListA = [(1,1),(1,2),(1,3),(1,4),(1,5)]
ListB = [(1,1),(2,1),(3,1)]

    for i in ListB:
        if i in ListA:
            print("There is an overlap")
            #choose coordinates again
        else:
            print("There is no overlap")
            #add to ListA and next ship's coordinate chosen

I would like for the program to check to see if any of the elements in A are in B by considering them collectively, instead of checking them individually.


set.intersection will find any common elements:

ListA = [(1,1),(1,2),(1,3),(1,4),(1,5)]
ListB = [(1,1),(2,1),(3,1)]
print(set(ListA).intersection(ListB))
set([(1, 1)])

Unless order matters it may be just as well to store the tuples in sets:

st_a = {(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)}
st_b = {(1, 1), (2, 1), (3, 1)}
print(st.intersection(st_b))

add it to your code with:

if st_a.intersection(st_b):
     print("There is an overlap")
else:
    print("There is no overlap")