-3

# Problem: Transfer the elements in list1 to list2, and finally list1 is empty

list1=["c++","java","python","sql","javascript"]
list2=[]

I wrote this for the first time:

for i in list1:
    a=list1.pop()
    list2.append(a)
print("list1=",list1)
print("list2=",list2)

result:

>>>
list1= ['c++', 'java']
list2= ['javascript', 'sql', 'python']

I soon realized that list1.pop() caused list1 to shrink continuously, i couldn't fetch list1, so the clever move changed to this, (then the problem that troubled me came)


list1=["c++","java","python","sql","javascript"]
list2=[]
for i in range(len(list1)):
    a=list1.pop()
    list2.append(a)
print(list1)
print(list2)

result:

>>>

list1= []
list2= ['javascript', 'sql', 'python', 'java', 'c++']

It was successful, because I didn’t know why it passed, so I added a few prints to see what happened in the process


list1=["c++","java","python","sql","javascript"]
list2=[]
for i in range(len(list1)):
    print(i)
    print(len(list1))
    print(range(len(list1)))
    print("__ __ __ __ __ __ __ __\n")
    a=list1.pop()
    list2.append(a)
print("list1=",list1)
print("list2=",list2)

result:

>>>
0
5
range(0, 5)
__ __ __ __ __ __ __ ___

1
4
range(0, 4)
__ __ __ __ __ __ __ ___

2
3
range(0, 3)
__ __ __ __ __ __ __ ___

3
2
range(0, 2)
__ __ __ __ __ __ __ ___

4
1
range(0, 1)
__ __ __ __ __ __ __ ___

list1= []
list2= ['javascript', 'sql', 'python', 'java', 'c++']

It stands to reason that list1 and range(len(list1)) are linked, and both are reduced at the same time.

But.. I ran it twice and the results showed: for i in range(len(list1)) did keep the initial state, let i take the range(len(list1)), and got i=0, 1, 2, 3, 4 Five values, But...for i in list1 ends at the third value "python"...

1 Answers1

0

The for instruction is creating an iterator from the object specified after in. This iterator is returning the next() of this iterator at each iteration. When you pop item out of list (first method) next() as no more value after 3 iterations and stops. When you use the range the range object and its iterator are created first and remain unchanged by the list pop.

Eric Mathieu
  • 631
  • 6
  • 11
  • “When you use the range the range object and its iterator are created first and remain unchanged by the list pop.”——I think your answer may be the best answer to my question,Because I am self-learning python, I am often troubled by some strange questions, and these questions are often critical. – han deepblue Jul 05 '20 at 20:36