Seth M. answered 02/07/20
Learn Python with Friendly, Personalized, Expert Tutoring!
Think of slice like a tool that you can customize and apply to arrays (and strings). When applied, this tool has a starting point, ending point, and an optional step. The structure is:
x = slice(start, end, step)
Once defined, you can then apply this tool to -- you can slice -- arrays. For example, suppose we wanted to slice out the elements from index 2 to index 5 in an array:
theArray = [0, 1, 2, 3, 4, 5, 6]
x = slice(0,5)
print (theArray[x])
The result would be [0, 1, 2, 3, 4]. As is generally the case, the "end" is the limit and is not included in the output.
The slicer can skip elements by adding a step, as follows:
theString = "alphabet soup is yummy"
x = slice(3,18,2)
print (theString[x])
This will output: hbtsu sy. It sliced out every 2nd item beginning at index three and up to index 18.