+ 2
How does the slicing [1:-1] work?
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] print(squares[1:-1]) The output is [1,4,9,16,25,36,49,64] and the 81 wasn't included,, why?
7 Respostas
+ 1
the -1 you mean?
that is actually the 3rd argument.
[1:1] == [1 = start at 1 : = all (or until the end here) 1 = steps of one]
some difficult/important things are:
the stopping argument is exclusive. so [1,5] is start at 1 and stop before you hit 5
when you use a negative 3rd argument the start and stop arguments are reversed.
so in [1:-1] it is actually
[1 == end at one exclusive so don’t count the last one : == start at the very last variable in the list -1 == go in steps of one]
also when you reverse the list by slicing it this way list[0] is now sort of list[1] (to understand this combine this and what I just wrote above)
mayssa rekik
+ 1
:) good going!
also don’t forget the 0 of course :)
0
I just didn't understand how the -1 in the second argument works, how do we get such a result?
0
Brave Tea so by giving the 1st argument the index 1 we excluded the 1st element of the list and by writing -1 we excluded the last element of the list?
0
yeah sort of. but it’s more about what happens to the list than excluding. I reckon this was a challenge and to be honest, challenges are good practise but aren’t always relevant.
it is more important to know what happens because of the various arguments than what is excluded.
my advice: go write a couple of lists and try different argument sets with the lists
this will give you a better understanding of them.
good luck :)
btw give lst[::-1] a try :)
0
Brave Tea will do thanks
Btw i know that one's for reverse :)