0

I have this code:

list1 = [1,2,3]
list2 = [3,4,5]
list3 = []


for i, j in zip(list1,list2):
    if i==j:
        list3 = i,j

How can I make list3 store elements that are the same between list1 and list2?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
DANKEST
  • 3
  • 2
  • Welcome to Stack Overflow. Please read [ask] and note that this is *not a discussion forum*. I tried to edit your question to ask it clearly, according to what I understand. To be clear: you want the result `list3` to be `[3]`, yes? Even though the `3`s are in different positions in the source lists? – Karl Knechtel Jan 09 '22 at 01:08
  • Hello and yes and this is the result i want to get to but according to mylittle knowledge in pytone i dont figuring it out how can it can be done – DANKEST Jan 09 '22 at 01:15
  • and sorry for this answers im new in this by the way – DANKEST Jan 09 '22 at 01:15
  • Good, that's all the information I needed. Please see the linked duplicate. – Karl Knechtel Jan 09 '22 at 01:19

1 Answers1

1

An easy way using Python's set intersection:

list1 = [1,2,3]
list2 = [3,4,5]
list3 = list(set(list1).intersection(list2))

print(list3)

or using a for loop:

list1 = [1,2,3]
list2 = [3,4,5]
list3 = []
for i in list1:
    if i in list2:
        list3.append(i)

print(list3)
krmogi
  • 2,588
  • 1
  • 10
  • 26