0

When I use this it includes 95 too. I think the code skips one item than adds the other. Can anyone explain why?

roll_number = [47, 64, 69, 37, 76, 83, 95, 97]
sample_dict = {'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97}
res = sample_dict.values()

for i in roll_number:
    if i not in res:
        roll_number.remove(i)

print("After removing unwanted elements from list", roll_number)
Skully
  • 2,882
  • 3
  • 20
  • 31
Murat
  • 1

1 Answers1

0

You should never modify an array over which you are looping inside the loop. Instead you can use the following list comprehension

roll_number = [number for number in roll_number if number in res]

Or if you want to use a for loop explicitly just store the result in a temporary list and assign it to roll_number after the loop

new_roll_number = []
for number in roll_number:
    if number in res:
        new_roll_number.append(number)
roll_number = new_roll_number