PYTHON LANGUAGE & SYNTAX · BATCH 2
09 · Indexing & Slicing
Indexing selects one item.
Slicing selects part of a sequence.
Indexing and Slicing
This syntax is commonly used with:
stringsliststuples
Python starts counting from 0.
Copper C o p p e r 0 1 2 3 4 5
01
Positive Index
product = "Copper"
print(product[0])Output:
CIndex 0 is the first item.
02
List Index
products = ["Copper", "Aluminum", "Nickel"]
print(products[1])Output:
Aluminum03
Negative Index
Negative indexes count from the end.
product = "Copper"
print(product[-1])Output:
rproducts[-1] returns the last list item.
04
Basic Slice
sequence[start:stop]
product = "Copper"
print(product[0:3])Output:
CopThe stop position is not included.
05–06
Omit Start / Omit Stop
Omit Start
product[:3]Output: Cop
If the start is omitted, slicing begins from the start.
Omit Stop
product[3:]Output: per
07
List Slice
products = [
"Copper",
"Aluminum",
"Nickel",
"Zinc"
]
selected = products[1:3]Result:
["Aluminum", "Nickel"]08
Slice with Step
sequence[start:stop:step]
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[0:7:2])Output:
[0, 2, 4, 6]09
Reverse with [::-1]
text = "Copper"
reversed_text = text[::-1]Result:
reppoCproducts[::-1] returns the list in reverse order.