Python 中的循环和列表

Loop and List in Python

使用下面的代码,我希望交换两个列表,并希望使用 Pop() 函数将 'names' 列表中的所有元素转换为“Excluded_list”。但它没有按预期工作,有人可以用下面的代码告诉问题吗??

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

swap/reprint 列表的代码

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

您正在修改 for 循环中的“names”,这意味着“for name in names”的计算结果与您预期的不同。

用 while 循环替换 for 循环。

while len(names):
    Excluded_list.append(names.pop())