C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Slice syntax forms:
Get elements from...
values[1:3] Index 1 through index 3.
values[2:-1] Index 2 through index one from last.
values[:2] Start through index 2.
values[2:] Index 2 through end.
values[::2] Start through end, skipping ahead 2 places each time.
Note: Python elements begin at index 0. So the first index (for slices or indexes) is zero.
Here: We continue up to (but not including) index 3, which is the value 400. So our result list has 200 and 300 in it.
Python program that slices list
values = [100, 200, 300, 400, 500]
# Get elements from second index to third index.
slice = values[1:3]
print(slice)
Output
[200, 300]
So: You can reduce an array length by one by using a second index of negative one. Leave the first index undefined.
Python program that slices, negative second index
values = [100, 200, 300, 400, 500]
# Slice from third index to index one from last.
slice = values[2:-1]
print(slice)
Output
[300, 400]
Tip: Programs with less confusing syntax tend to develop fewer bugs over time. So lazy programmers are sometimes the best ones.
Python program that slices, starts and ends
values = [100, 200, 300, 400, 500]
# Slice from start to second index.
slice = values[:2]
print(slice)
# Slice from second index to end.
slice = values[2:]
print(slice)
Output
[100, 200]
[300, 400, 500]
Python program that slices string
word = "something"
# Get first four characters.
part = word[:4]
print(part)
Output
some
Tip: This allows us to quickly access all odd or even elements in an array. No complicated loops are required.
Python program that uses step, slices
values = "AaBbCcDdEe"
# Starting at 0 and continuing until end, take every other char.
evens = values[::2]
print(evens)
Output
ABCDE
However: Slicing alleviates some of these hassles. But this too can be a problem. Our program might silently fail, causing confusion later.
Python program that uses invalid indexes
values = [9, 8, 7, 6]
# This causes no error.
test = values[555:555:5555]
print(test)
Python program that causes TypeError
values = ["carrot", "rat"]
# Must use indexes or None.
test = values["friend":"dog"]
print(test)
Output
Traceback (most recent call last):
File "...", line 7, in <module>
test = values["friend":"dog"]
TypeError: slice indices must be integers or None
or have an __index__ method
So: If you are trying to slice a string, list or other built-in type, pay no attention to the slice method. It won't help you.
Python program that creates slice object
# Create a slice object.
example = slice(1, 10, 0)
print(example.start, example.stop, example.step)
Output
1 10 0