+ 11

Python quiz - How does this work?

a = [0, 1, 2, 3] for a[-1] in a: print(a[-1]) Output is 0, 1, 2, 2 How does this work?

1st Mar 2019, 1:04 AM
[Abandoned]
[Abandoned] - avatar
9 ответов
+ 22
The for loop iterates over the values of list "a" and assings them to a[-1]. # Initial value a = [0, 1, 2, 3] First iteration (a[0] == 0): a[-1] = 0 # a = [0, 1, 2, 0] Second iteration (a[1] == 1): a[-1] = 1 # a = [0, 1, 2, 1] Third iteration (a[2] == 2): a[-1] = 2 # a = [0, 1, 2, 2] Fourth iteration (a[3] == 2): a[-1] = 2 # a = [0, 1, 2, 2].
1st Mar 2019, 4:08 AM
Diego
Diego - avatar
+ 10
To be honest I want to know the answer too. I have been puzzled by this quiz too
1st Mar 2019, 1:29 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
yves houedande Please ask your question on a separate post. And remember to use the search bar to avoid duplicates. https://www.sololearn.com/discuss/1704704/?ref=app
2nd Mar 2019, 1:16 AM
Diego
Diego - avatar
+ 2
code: a = [0,1,2,3] for a[0] in a: print(a) output: [0, 1, 2, 3] [1, 1, 2, 3] [2, 1, 2, 3] [3, 1, 2, 3] code: a = [0,1,2,3] for a[1] in a: print(a) output: [0, 0, 2, 3] [0, 0, 2, 3] [0, 2, 2, 3] [0, 3, 2, 3] 'a' is global variable, but in the loop 'a' it's a local variable. the digits from the global array are passed to the second element of the local array. I remind you that the index -1 means the last element of the array. that's why code: a = [0,1,2,3] for a[-1] in a: print(a) output: [0, 1, 2, 0] [0, 1, 2, 1] [0, 1, 2, 2] [0, 1, 2, 2] 'a' is an array in a loop, we can get any element of it, so code: a = [0,1,2,3] for a[-1] in a: print(a[-1]) output: 0 1 2 2
1st Mar 2019, 2:38 AM
Before
Before - avatar
+ 1
i'm a biginner and i learn english too,so please for my way of speaking my question is :what is local and global variable
2nd Mar 2019, 12:55 AM
yves houedande
yves houedande - avatar
+ 1
can someone explain it a bit more clearly??
2nd Mar 2019, 6:36 AM
Nitesh Solanki
Nitesh Solanki - avatar
0
What the result for this: Object-Oriented Programming Classes question 2?
4th Mar 2019, 5:08 PM
Abo K. Thominou Vertu
Abo K. Thominou Vertu - avatar
0
by knowledge
4th Mar 2019, 11:00 PM
Troy Peppers
Troy Peppers - avatar
- 5
0,1,1,2
1st Mar 2019, 5:47 PM
Ananth Yuvi
Ananth Yuvi - avatar