+ 1

Guys please explain the print part of each

squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[-1:4:1]) squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[-1:4:-1]) #is it possible to have -4 for the step part? is yes how does it work?

31st Jul 2020, 4:03 PM
Coder
Coder - avatar
7 Réponses
+ 6
Coder squares[start:stop:step] for print(squares[-1:4:-4]) here, start = -1 stop = 4 step = -4 +----+----+----+----+----+----+----+----+----+----+ | 0 | 1 | 4 | 9 | 16 | 25| 36 | 49 | 64 | 81| +----+----+----+----+----+----+----+----+----+----+ 0 1 2 3 4 5 6 7 8 9 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ^ ^ | | stop start So we can see from the figure above S is at 81 and E is at 16. 1) squares[start] => squares[-1] is printed which is 81 2) squares[start+step] => squares[-1+(-4)] = squares[-5] is printed which is 25 Hence, we have [81, 25]
31st Jul 2020, 5:14 PM
minirkk
minirkk - avatar
+ 4
https://stackoverflow.com/questions/509211/understanding-slice-notation a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items Similarly, step may be a negative number: a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed here's a code, if you still don't understand let me know. https://code.sololearn.com/cAQBZ3dHmbKW/?ref=app
31st Jul 2020, 4:22 PM
minirkk
minirkk - avatar
+ 3
-1 is the first number from the end to the first and -4 is the fourth number from the end to the first. But when we write [-1: -4] the number four does not count and the number before it counts. And if we put the third number in the bracket [ -1: -4: -1] the numbers are one by one Prints from end to first.
31st Jul 2020, 4:45 PM
‎Siamak Naseri
‎Siamak Naseri - avatar
+ 1
coder This is the method of cutting lists and listing indexes that rkk has explained to you
31st Jul 2020, 5:52 PM
‎Siamak Naseri
‎Siamak Naseri - avatar
+ 1
Or print(squares[-1:-6:-4]) Good luck ;)))
31st Jul 2020, 5:58 PM
‎Siamak Naseri
‎Siamak Naseri - avatar
0
i know it's slice list but when i made my own examples i found there is no rules for the bounds. It depends on example. I don't understand the negative bounds mixed with positive bounds.
31st Jul 2020, 4:17 PM
Coder
Coder - avatar
0
thx for your answers. how about this? which prints [81, 25] print(squares[-1:4:-4]) ^
31st Jul 2020, 5:07 PM
Coder
Coder - avatar