Why the answer of the code below is 1,8,2,3,5,6,8 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why the answer of the code below is 1,8,2,3,5,6,8

a = [1,1,2,3,5,6,8] for a[1] in a: pass print (a)

14th May 2020, 3:12 PM
Ravi Kumar Verma
Ravi Kumar Verma - avatar
6 Answers
+ 4
Ravi Kumar Verma Usually in the for loop, if we say for i in a: #a=[1,2,3] print(i) We get the output as 1,2,3 because each element of list "a" is assigned to "i" in each iteration. In the example you have taken each element of list "a" gets assigned to "a[1]" and finally you get the output as 1,8,2,3,5,6,8 because the last element which is assigned to a[1] is 8 which is the last element of the list which is specified. It can better be understood if you keep the "print(a)" in the loop rather than outside of it. See the below code... This was cool question. I myself took time to understand...😅😅 https://code.sololearn.com/cZI6Lcs5djB4/?ref=app
14th May 2020, 4:37 PM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
+ 2
Ravi Kumar Verma Exactly...
14th May 2020, 4:47 PM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
+ 1
Kiran Deep Naidu thanks so much...
14th May 2020, 4:42 PM
Ravi Kumar Verma
Ravi Kumar Verma - avatar
+ 1
Soo in for i in a: ( here i represent the index) and in for a[1] in a:(what is a[1]).i think it means the index in the list to be replaced.
14th May 2020, 4:45 PM
Ravi Kumar Verma
Ravi Kumar Verma - avatar
+ 1
Thanks ☺️
14th May 2020, 4:51 PM
Ravi Kumar Verma
Ravi Kumar Verma - avatar
0
😊😊
14th May 2020, 4:42 PM
Kiran Deep Naidu
Kiran Deep Naidu - avatar