Categories

CUC (6) CUCM (26) Jabber (6) Python (2) Routing (3) Solarwinds Orion NPM (4) switching (1) Video (6) voice (2)

Monday, 10 July 2017

Python object indexing and slicing; lists, strings and tuples.

Wonder where this is leading to, anyway. Let's kick off.


Because lists are sequences, indexing and slicing work the same way for lists as they do for strings (which are essentially a definition of ordered collections of characters, so accessible by position). The key to slicing and indexing is the offset. Python starts at 0 and ends at on less than the length of the string or list. This is important, because the latest character in a string or object in a list is not addressable. You can also use negative offsets, think of this as counting backward from the end. The picture below shows how offsets can be used.





Consider the following string and let's pull the first and last character of that string:

>>> S="flyffy bunny"
>>> S[0],S[-1]
('f', 'y')
>>> 

and slicing (extracting a section):

>>> S[-5:-1]           #negative offset slicing, count from right
'bunn'
>>> S[0:3]
'fly'

another example:

>>> S[1:-1]
'lyffy bunn'

>>> S[0:-1]

'flyffy bunn'

or just apply it straight:

>>> 'flyffy bunny'[1:3]

'ly'

>>> 'flyffy bunny'[slice(1,30)]
'lyffy bunny'


Now consider the following list, containing 3 objects:

>>> L = ['spam', 'Spam', 'SPAM!']

>>> L[2]                #offset starts at 0, which is the object on the left 

'SPAM!'


>>> L[2]                  #Negative; count offset from the right
>>> L[1:]                 # Slicing fetches sections (1st offset from left)

['Spam', 'SPAM!']




Slices can be used to extract columns of data, and to prefix or remove leading and trailing text.


In short:


• S[1:3] fetches items at offsets 1 up to but not including 3.
• S[1:] fetches items at offset 1 through the end (the sequence length).
• S[:3] fetches items at offset 0 up to but not including 3.
• S[:−1] fetches items at offset 0 up to but not including the last item.
• S[:] fetches items at offsets 0 through the end—making a top-level copy of S.

Extended slicing:

As of python 2.3, splice expressions allow  a third, optional index:  the step/stride.  

>>> S="123456789012345567890"
>>> S[0:10:2]

'13579'

This extended slice, takes characters between offset 0 and 10 by steps of 2, so 1 3 5 7 and 9

You can also use a negative stride.

No comments:

Post a Comment