+ 3

What is the output of this code ?

a = [ x for x in range(4) ] print(sum(a[1::-2] + a[::-3])) unable to understand negative steps... plz explain it in step by step manner.. Thanks

31st Aug 2018, 11:54 AM
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷 - avatar
5 Answers
+ 10
Take note that: a[start:end:step] ---> since the `step` is negative, the slice starts at index `start` and goes up to `end+1` (in other words, `end` is not inclusive, just like when `step` is positive and goes up to `end-1`). With that knowledge, what the slices are doing: a[1::-2] ---> the start is 1 and the default end is -1 not inclusive or 0 inclusive, with a step -2. Indexes the slice reaches: 1 Thus, a[1::-2] == a[1] == [1] a[::-3] ---> the default start is len(a)-1 and the default end is -1 not inclusive or 0 inclusive, with a step -3. Indexes the slice reaches: 3, 0 Thus, a[1::-2] == a[3] + a[0] == [3, 0] If you still don't understand, my advice is you should try with a bigger list so you have more data to analyze. Right now your list has only 4 elements so it is difficult to understand what the slices are really doing.
31st Aug 2018, 12:10 PM
Eduardo Petry
Eduardo Petry - avatar
+ 5
0123 [1::-2] begin at index 1....1 go two steps back as long as possible... not possible... first sum is 1 0123 [::-3] since you go backward start at the end. 3 go back 3steps ...0. no more step possible second sum is 3+0=3
31st Aug 2018, 12:39 PM
Oma Falk
Oma Falk - avatar
+ 2
I got it... Thanks print(a[1::-2]) print(a[::-3) output ---- [1] [3,0] print(a[1::-2] + a[::-3]) output --- [1,3,0] print(sum(a[1::-2] + a[::-3])) output--- 1+3+0 = 4
31st Aug 2018, 3:09 PM
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷 - avatar
+ 1
Thanks Eduardo Petry so what is the output after executing print statement ??
31st Aug 2018, 2:53 PM
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷 - avatar
+ 1
Oma Falk If we run these two print statement, print(a[1::-2]) print(a[::-3) output ---- [1] [3,0] Then what is the output of print(sum(a[1::-2] + a[::-3])) ???? If we run above print statement in Anaconda jupyter IDE, we get the output 4...How ??
31st Aug 2018, 2:59 PM
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷
🌷Ⓛⓤ𝔹𝓝ⓐ Ⓚⓗ𝔸ⓝ🌷 - avatar