list1 = [4,5,6]

for n in list1:
    print "list1:", list1
    print "n:", n
    list1 = [7,8,9]

output:
list1: [4, 5, 6]
n: 4
list1: [7, 8, 9]
n: 5
list1: [7, 8, 9]
n: 6


list "list1" is not affecting even though it is re-assigned in for loop.
My intention if "list1" has to be dynamically changed inside for loop, but it is not happening.I think "list1"(inside for loop) is different object from that of actual "list1".
Is there any trick to make it work in the way I want?

It is never a good idea to change the same object you are iterating over in the loop. Simply create a new object and do the changes on that object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.