Talk:Python Concepts/Operators

From Wikiversity
Jump to navigation Jump to search

Slicing[edit]

Reading an example:

Type: >>> x = "0123456789" Now Type: >>> x[1:-1:3] '147'

I just don't get how it gives such a result. Re-reading relevant description before the code didn't help. Please add a more detailed explanation! Thank you in advance.

I added a note on the page that links to the relevant documentation as to what is going on here. The syntax is explained that given x[i:j:k]
  • i represents the position of the element to start with; defaults to '0'
  • j represents the position of the element to end with; defaults to the length of the sequence data-type
  • k represents the step (e.g. counting every other element, or counting every third element, etc.)

So if x = "0123456789"

Then the operation x[1:-1:3] would mean: Start at position 1 (which is equal to '1') then go to position -1 (which is equal to '9' because -1 is the very last element of a sequence) and only include every 3rd element.

So '1' would be added to the result and then it would move 3 elements forward which would be '4' which is added to the result and then move 3 steps forward which would be '7' and then it would move 3 steps forward but reach the end of the sequence before it got to the next 3rd position. Therefore the result would be '147'. Hope that helps. Devourer09 (t·c) 01:36, 9 May 2011 (UTC)