I need to write a code, using loops, to find out if there is any common element in two lists. So, I wrote the following:
l1 = eval(input("Enter a list: "))
l2 = eval(input("Enter another list: "))
for i in range (len(l1)):
for j in range (len(l2)):
if l1[i] == l2[j]:
print("Overlapped")
break
else:
print("Separated")
However, what I get as output is this:
Enter a list: [1,34,543,5,23,"apple"]
Enter another list: [54,23,6,213,"banana"]
Overlapped
Separated
Since the lists do have a common member, it should only print "Overlapped", but it ends up printing "Separated", too.
How do I fix this? I'm using python 3.7
Thank you so much!!
Since you'll need to break out of both loops for the
elseto work as you expect, I think it'll be easier to just not use theelseat all here. If you define your code in a function, you can usereturnto break out of both loops at the same time.For example:
Sample: