954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Need help understanding negative lists

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... :(

Cenchrus
Newbie Poster
19 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

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.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

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]

Cenchrus
Newbie Poster
19 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

Actually, I just figured it out ;) thanks

Cenchrus
Newbie Poster
19 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: