python - Weird for loop statement -


this question has answer here:

i saw loop , didn't quite understood why last print 2. why isn't 3 ?

a = [0, 1, 2, 3]  a[-1] in a:     print(a[-1]) 

out:

0 1 2 2 

the for loop uses a[-1] target variable. for loop assigns each value in list 1 variable. happens also last element in same list.

so list changes each step through loop:

>>> = [0, 1, 2, 3] >>> a[-1] in a: ...     print ... [0, 1, 2, 0]  # assigned a[0] == 0 a[-1] (or a[3]) [0, 1, 2, 1]  # assigned a[1] == 1 a[-1] [0, 1, 2, 2]  # assigned a[2] == 2 a[-1] [0, 1, 2, 2]  # assigned a[3] == 2 (since previous iteration) a[-1] 

the one-but-last iteration assigns puts a[2] a[3] (or a[-2] a[-1]), , why, when last iteration takes place, see 2 again.

the for loop grammar takes generic target_list assignment target, assigment statement. not limited simple names in assignments, , neither in for loop.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -