Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6
Try writing that in the code playground: a[-1] is 3, but if we replaced a[-1] in the loop: for 3 in a It won't work because it cannot assign to literal. Let's look at a regular for loop with the popular "i" variable for i in a: print(i) we have a number of turns, each turn has "i" assigned to a different number in "a" try: a[-1] = 0 and print(a) it changed the original list! Now back to the original code: Python takes a[-1] and assigns it to the corresponding value in "a" on each turn which modifies the original list. We have four turns: 1. a[-1] = 0 2. a[-1] = 1 3. a[-1] = 2 4. a[-1] = 2 as well; because we are already in the last turn which returns 2. more like that: for i in a: a[-1] = i
29th Jun 2020, 5:51 PM
Ali Abdelhady
Ali Abdelhady - avatar
+ 6
If you use the range function, the output will be equal to whether you are used by a normal iteration. for a[-1] in range(len(a)): print(a[-1])
29th Jun 2020, 5:58 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
+ 3
Jessel baraka , Have you copied the comment from Ali Abdelhady ?
30th Jun 2020, 5:10 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
- 2
Try writing that in the code playground: a[-1] is 3, but if we replaced a[-1] in the loop: for 3 in a It won't work because it cannot assign to literal. Let's look at a regular for loop with the popular "i" variable for i in a: print(i) we have a number of turns, each turn has "i" assigned to a different number in "a" try: a[-1] = 0 and print(a) it changed the original list! Now back to the original code: Python takes a[-1] and assigns it to the corresponding value in "a" on each turn which modifies the original list. We have four turns: 1. a[-1] = 0 2. a[-1] = 1 3. a[-1] = 2 4. a[-1] = 2 as well; because we are already in the last turn which returns 2. more like that: for i in a: a[-1] = i or a = [4,9,6,2] print(a[0]) print(a[1]) print(a[2]) print(a[3]) or Python 2 print range(1,5) print range(10) print range(1,11) print range(0) print range(1,10,2) 0r python3 print(list(range(1,5))) print(list(range(10))) print(list(range(1,11))) print(list(range(0))) print(list(range(1,10,2))) It is good to be multi diverse guys feels good
30th Jun 2020, 8:37 AM
Jesse Wasike
Jesse Wasike - avatar