Saturday, 2 September 2017

Python slicing

 Slicing working in python 
 P | y | t | h | o | n |
 +---+---+---+---+---+---+
  0   1   2   3   4   5 
 -6  -5  -4  -3  -2  -1
a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array
a[start:end:step] # start through not past end, by step
The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning
a[-1] # last item in the array 
a[-2:] # last two items in the array 
a[:-2] # everything except the last two items
 
>>> items = [0, 1, 2, 3, 4, 5, 6]
>>> a = slice(2, 4)
>>> items[2:4]
[2, 3]
>>> items[a]
[2, 3]
>>> items[a] = [10,11]
>>> items
[0, 1, 10, 11, 4, 5, 6]
>>> del items[a]
>>> items
[0, 1, 4, 5, 6]

 

No comments:

Post a Comment