-1

When I move items from list "X" to anther list "A", but some items are missing.

Here is my code.

X=list(range(2,11))
print(X)
A=list()
for x in X:
       A.append(x)
       X.remove(x)
       print("A is ", A)
       print("X is ", X)

I expected X =[], A =[2,3,4,5,6,7,8,9,10],

but the result was

A is  [2, 4, 6, 8, 10]
X is  [3, 5, 7, 9]

the odd numbers aren't moved. I want to know why they are not moved and how to move them.

I'm new to python programing, and any help will be greatly appreciated.

Subbu VidyaSekar
  • 2,503
  • 3
  • 21
  • 39
Taejin
  • 17
  • 8
  • 6
    Don't change list while iterating over it – buran Jan 20 '21 at 07:25
  • 4
    This is a classic mistake: looping over a list while modifying it. Python keeps track of what the current position in the list `X` is, but since you're removing elements during every iteration, that position is no longer correct. (also, don't name variables `x` and `X` - that's a very bad habit) – Grismar Jan 20 '21 at 07:26
  • Is there any reason why can't you just move it the normal way? You want to reverse the list? – user202729 Jan 20 '21 at 07:26
  • You can copy the list and work from the copy, e.g. `for x in list(X):` – DisappointedByUnaccountableMod Jan 20 '21 at 07:34
  • Thanks guys, I was making some codes finding out prime numbers from 2 to a given number. And I made two lists, the X from 2 to 10, and the prime number list. Anyway, I found what was problem. Thank you so much..!!! – Taejin Jan 20 '21 at 12:56
  • Really appreciate your advice.. – Taejin Jan 20 '21 at 13:31

1 Answers1

1
    X=list(range(2,11))
    print(X)
    A=list()
    X=X[::-1]
    while X:
       A.append(X.pop())
       print("A is ", A)
       print("X is ", X)

Instead of removing first reverse the X and pop the elements from X and append it to A.