+ 2

Variable in for loop

a =[1,2,3,4,5] i=4 for a[i] in a: print(a[i]) Can some one explain this code Output 1 2 3 4 4

20th Feb 2022, 5:34 PM
Prabhas Koya
1 Antwort
+ 3
The for loop will loop through each element in the provided sequence. In this case a. It will assign its value to the provided name. In this case the name provided points to the element at index 4 of the list a. So, what happens is during each iteration of the loop the element at the 4th index of a is reassigned the value of the current element from the index the loop is on. Like; a[4] = 1 # 1st iteration a[4] = 2 # 2nd iteration Etc. This will change the list A with each iteration of the loop as follows; [1,2,3,4,1] # 1st iteration [1,2,3,4,2] # 2nd iteration Inside the loop it just prints out whatever value was just assigned to the 4th index of the list. You could see these changes of you added a print statement that output the current state of the list with each iteration.
20th Feb 2022, 7:17 PM
ChaoticDawg
ChaoticDawg - avatar