0

With below code, I was expecting to swap two lists and was expecting all the elements from 'names' list to 'Excluded_list'using Pop() function. But it is not working expectedly, can someone please tell the issue with below code ??

names=['Ram','Sham','Mohan','John','Kuldeep']
Excluded_list=[]
print('names list',names)
print('Excluded list ',Excluded_list)

Code to swap/reprint lists

for name in names:
    Excluded_list.append(names.pop())
print('names list',names)
print('Excluded list ',Excluded_list)

1 Answer 1

1

You are modifying "names" in the for-loop, which means that the "for name in names" does not evaluate as you expect.

Replace the for-loop with a while-loop.

while len(names):
    Excluded_list.append(names.pop())
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Kim, It really helped. But I am still confused over For loop failure, If possible can you please explain why it fails??
You should not modify the list (here names) you are iterating over. This is explained in this answer
Got it now .Thanks a lot !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.