Bucle for python | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 3

Bucle for python

hello guys this is my first post, there will be someone to help me understand the python for loop especially with this code A = [1,2,3,4,1] for n in A: A[n]=0 print(A) oputput: [0, 0, 3, 0, 1] why the output is that is not supposed to be pure zeros pls help me understand!! and thanks

21st Apr 2018, 4:08 PM
PaI2tition
PaI2tition - avatar
8 Respuestas
+ 20
It's like this for loop runs 1--> n=1 A[1] = 0 A = [1, 0, 3, 4, 1] now 2nd element is 0 2--> n = 0 A[0] = 0 A = [0, 0, 3, 4, 1] 3--> n= 3 A[3] = 0 A = [0, 0, 3, 0, 1] 4--> n = 0 already value is 0 so list makes no difference. 5--> n = 1 already value is 0
21st Apr 2018, 4:21 PM
ūüĆõDTūüĆú
ūüĆõDTūüĆú - avatar
+ 17
PaI2tition list[list[4]] is out of range & not list[4] list[4] = 8 so list[list[4]] = list[8] = error please go through the explanation again ... take ur time to understand...
21st Apr 2018, 7:04 PM
ūüĆõDTūüĆú
ūüĆõDTūüĆú - avatar
+ 15
PaI2tition list[3] = 4 list[4] = 8 therefore list[list[3]] = list[4] = 8 when u put 4 inside list[list[4]] list[4] = 8 list[8] = error, since the index is out of range... list contains 6 elements so highest possible index can be 5... index start from 0
21st Apr 2018, 6:53 PM
ūüĆõDTūüĆú
ūüĆõDTūüĆú - avatar
21st Apr 2018, 4:25 PM
Koushik Naskar
Koushik Naskar - avatar
+ 2
n = A[0] = 1 [1,0,3,4,1] n = A[1] = 0 [0,0,3,4,1] n = A[2] = 3 [0,0,3,0,1] n = A[3] = 0 [0,0,3,0,1] n = A[4] = 1 [0,0,3,0,1] Please ask if it's still unclear. Oh, ūüĆõDTūüĆú was faster.
21st Apr 2018, 5:12 PM
Timon Paßlick
+ 2
sorry bro, iam not a native english so its hard for me to understand and thanks for all :)
21st Apr 2018, 7:26 PM
PaI2tition
PaI2tition - avatar
+ 1
ty all guys i have another question why this code print 8 and why if I put the index 4 gives me error, if u can explain i will be grateful :) , sorry guys for my nab questions but i really want to learn, list = [1,1,2,4,8,10] print(list[list[3]]) output: 8
21st Apr 2018, 6:42 PM
PaI2tition
PaI2tition - avatar
+ 1
but look this DT index 4 is out of range https://code.sololearn.com/cZF71IQGO7lp/?ref=app
21st Apr 2018, 7:02 PM
PaI2tition
PaI2tition - avatar