-3

I'm trying to make a program that removes everything that is not in list x from list a. But it only removes even numbers from the list a. Here's my code:

n = int(input())
a = []
for i in range(1, n + 1):
  a.append(str(i))
x = [s for s in input().split()]
for o in a:
  if o not in x:
    a.remove(o)
print(a)
Jonas
  • 49
  • 7
  • Please explain what is currently not working in your code. Include any error messages you might be getting. Also, please ensure you edit your question to add the extra explanation. Do not use the comment space to expand the clarity of your question. – idjaw Jul 23 '17 at 17:29
  • 4
    Oh, please, _please_ don't remove items from a list while iterating over it! – ForceBru Jul 23 '17 at 17:30

1 Answers1

3

The correct way of doing it is:

a = [o for o in a if o in x]

A side note: x = [s for s in input().split()] is redundant, it does the same as:

x = input().split()
Błotosmętek
  • 12,717
  • 19
  • 29