Python intersection value between two sets and the position of Intersection

Viewed 18
firstSet = [65,42,78,83,23,57,29]
secondSet = [67,73,43,48,83,57,29]
Intersection = []
for i in firstSet:
  if i in secondSet:
    Intersection.append(i)
    firstSet.remove(i)
print("Intersection is ", Intersection)
print(firstSet)

Why I can't use this one ( because if i use this one it will not remove 29 ) but this code below able to do it? I have searched until I found out that I need to put [:] behind firstSet in for loop but I still can't figure it out why I need to do that


firstSet = [65,42,78,83,23,57,29]
secondSet = [67,73,43,48,83,57,29]
Intersection = []
for i in firstSet[:]:
  if i in secondSet:
    Intersection.append(i)
    firstSet.remove(i)
print("Intersection is ", Intersection)
print(firstSet)

and also I found in my homeworks that the intersection is {57,83,29} ( Mine is {83,57,29}) I'm still not understand why is it 57 first instead of 83 since using for loop to check it start with the first element in array which is at position 0 and you will find out that the first number that is in intersection is 83

0 Answers
Related