What is the output of this code? print('gameofdice'[ ::2]) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the output of this code? print('gameofdice'[ ::2])

Answer is gmodc. But I didnot know how it cames. Can anyone help me to understand this

20th Jul 2020, 7:16 AM
Mohanapriya P
7 Answers
+ 7
[start:stop:step] - start index (here 0) - stop index (here the end of the string) - step = 2 'gameofdice' ^ ^ ^ ^ ^ 0 2 4 6 8
20th Jul 2020, 7:27 AM
Théophile
Théophile - avatar
+ 6
This will print "gmodc" as mentioned by Pranav Kalro. In the code above, you haven't given the starting and ending value. So, it will take the starting of the list and ending value as the ending value of list by default.. Moreover, you've given the step of 2 so, it will print all the strings with the 2nd element.. So, the output will be: g-0(index,can be taken as 2nd letter) letter(will be printed) a-1st letter m- 2nd letter (will be printed) e-1st letter o-2nd letter(will be printed) f-1st letter d-2nd letter (will be printed) i-1st letter c-2nd letter (will be printed) e-1st letter Observe the above code carefully and analyze what's happening there.
20th Jul 2020, 7:34 AM
Arctic Fox
Arctic Fox - avatar
+ 4
The output is 'gmodc'. It is giving every alternate letter of the word 'gameofdice'.
20th Jul 2020, 7:23 AM
Pranav Kalro
Pranav Kalro - avatar
+ 4
This code may help you understand how string/list indexing works. https://code.sololearn.com/c97WRsMP3F6b/?ref=app
20th Jul 2020, 7:26 AM
李立威
+ 2
Thank you so much
20th Jul 2020, 7:24 AM
Mohanapriya P
+ 2
Tq all
20th Jul 2020, 7:28 AM
Mohanapriya P
+ 2
[::2] skips and jumps to the 2nd element of the string "gameofdice" ... thus if you consider gameofdice as g:0 a:1 m:2 e:3 o:4 f:5 d:6 i:7 c:8 e:9 then it executes as 02468 i.e- gmodc #hope it helps
21st Jul 2020, 8:48 PM
Rashi Mishra
Rashi Mishra - avatar