I have 2 lists, for example:
list1 = [1, 2, 2, 3, 3, 4] list2 = [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
I want to get a list 3 which will include all numbers from list2 matching the numbers from list1:
list3 = [1, 1, 2, 2, 3, 3, 4, 4, 4]
I was trying to use 2 while loops to go through list1 and list2 and match numbers, but it gives me wrong number of values:
listO = [1, 2, 2, 3, 3, 4]
listX = [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
x_temp = []
a = 0
b = 0
while a < len(listO):
while b < len(listX):
if listO[a] == listX[b]:
x_temp.append(listX[b])
print("Outlier a:" , listO[a] )
listX.remove(listX[b])
b+=1
b=0
a+=1
list3 = [1, 2, 2, 3, 3, 4, 4]
Is there any way to do it using loops?
- Please do NOT provide solution using set() it doesn`t work for my lists!
Advertisement
Answer
With a for loop:
listO = [1, 2, 2, 3, 3, 4]
listX = [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5]
x_temp = []
for x in listX:
if x in listO:
x_temp.append(x)
# [1, 1, 2, 2, 3, 3, 4, 4, 4]