+ 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
8 odpowiedzi
+ 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
+ 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...
+ 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
+ 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.
+ 2
sorry bro, iam not a native english so its hard for me to understand and thanks for all :)
+ 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
+ 1
but look this DT index 4 is out of range
https://code.sololearn.com/cZF71IQGO7lp/?ref=app