简体   繁体   中英

Python pop and append are not moving all elems in list1 to list 2

Why do pop and append not finish out the entire loop? My first guess was that pop didn't readjust the index of the original list, but that doesn't appear to be true when I print(txt[0]) to confirm it's still at the front. I'm trying to figure out why the below does not work. Thank you.

txt = 'shOrtCAKE'
txt = list(txt)
new_list = []

for x in txt:
    value = txt.pop(0)
    new_list.append(value)

print(new_list)
print(txt)
print(txt[0])

You shouldn't modify the list while iterating over it. Instead use this code

for x in txt:
    value = x
    new_list.append(value)
txt = [] # assuming you want txt to be empty for some reason

But then if you end up printing txt[0] you'll end up with error as the list index will be out of range

However you don't really need to be looping. Just do the following:

new_list = txt[:] # [:] ensures that any changes done to txt won't reflect in new_list

You should not remove elements from a list that you are iterating over. In this case, you are not even using the values of the list obtained during iteration.

There are various possibilities if you still want to use pop , which don't involve iterating over txt . For example:

  • Loop a fixed number of times ( len(txt) computed at the start):
for _ in range(len(txt)):
    new_list.append(txt.pop(0))
  • Loop while txt is not empty:
while txt:
    new_list.append(txt.pop(0))
  • Loop until pop fails:
while True:
    try:
        new_list.append(txt.pop(0))
    except IndexError:
        break

Of course, you don't have to use pop . You could do this for example:

new_list.extend(txt)  # add all the elements of the old list
txt.clear()  # and then empty the old list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM