Alan Gauld via Tutor wrote: > On 29/06/17 03:14, shubham goyal wrote: > >> This Question is asked in some exam. i am not able to figure it out. >> >> a = [0, 1, 2, 3] >> for a[-1] in a: >> print(a[-1]) >> >> its giving output 0 1 2 2 >> >> it should be 3 3 3 3 as a[-1] belongs to 3. >> can anyone help me figuring it out. > > This is quite subtle and it took me a few minutes to figure > it out myself. > > It might be clearer if we print all of 'a' instead > of a[-1]: > >>>> for a[-1] in a: > ... print(a) > ... > [0, 1, 2, 0] > [0, 1, 2, 1] > [0, 1, 2, 2] > [0, 1, 2, 2] > > What is happening is that a[-1] is being assigned the value > of each item in a in turn. The final iteration assigns a[-1] > to itself, thus we repeat the 2. > > Another way to see it is to convert the for loop to > a while loop: > > for variable in collection: > process(variable) > > becomes > > collection = [some sequence] > index = 0 > while index < len(collection): > variable = collection[index] > process(variable) > index += 1 > > Now substitute your values: > > collection = [0,1,2,3] > index = 0 > while index < len(collection): > collection[-1] = collection[index] > print(collection[-1]) > index += 1 > > Does that help?
The simplest rewrite is probably >>> a = [0, 1, 2, 3] >>> for tmp in a: ... a[-1] = tmp ... print(tmp) ... 0 1 2 2 which should clarify how the list is modified while iterating over it. The takeaway is that for ... in [value]: pass is equivalent to ... = value There are a few other implicit ways to assign a value, with varying generality: >>> with open("tmp.txt") as a[0]: pass ... works, but >>> import os as a[0] File "<stdin>", line 1 import os as a[0] ^ SyntaxError: invalid syntax and >>> try: 1/0 ... except Exception as a[0]: pass File "<stdin>", line 2 except Exception as a[0]: pass ^ SyntaxError: invalid syntax are forbidden by the language. The only case -- other than standard name binding -- I find useful is unpacking in a for loop: >>> for hi, lo in ["Aa", "Zz"]: ... print(hi, "-", lo) ... A - a Z - z _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor