Can someone tell me, step by step, how python interprets this code?

Numbers = [1,2,3,4,5,6,7,8,9,10]
Numbers[8:3:-1]

I know that the "-1" is the counting bit of it, and it goes in the negative direction, but I'm lost on everything else... :(

The standard terminology is to call the three slice arguments start, stop and step

L[start:stop:step]

The elements in the returned list are

L[start], L[start + step], L[start + 2*step], L[start + 3*step], ...
  • step cannot be zero and defaults to 1
  • stop must not be understood as a last element, but as an unreachable bound. If start + k*step reaches the bound, the item with this index is not in the returned sequence.
  • If start (or stop) is < 0, python adds the length of the list to its value before doing anything.
  • Then if step < 0 but stop >= start, the returned list is empty
  • Similarly if step > 0 and stop <= start.
  • If stop is empty, it means 'no bound', like in L[2::1] .
  • If start is empty, it means start from the first or the last element depending on step > 0 or step < 0

For example

L[::-1]

starts from the last element with no bound and step -1, it reverses the list.

I'm sorry, but I still did not understand how python specifically interprets this code:

Numbers = [1,2,3,4,5,6,7,8,9,10]
print Numbers[8:3:-1]

If the code was like this:

Numbers = [1,2,3,4,5,6,7,8,9,10]
print Numbers[1:11:2]

I would want an answer like this:

"Python sees that in the Start position you have 1, which tells it to start at index one, inclusive.
Python sees that the Stop index is 11 , exclusive.
Python sees that you want it to count every second element from index one.
The output will then be [2, 4, 6, 8, 10]

Actually, I just figured it out ;) thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.