2. Slicing
A slice takes a part of a list without changing the original. The syntax is:
start— index where the slice begins. Included. Default:0(the beginning).stop— index where the slice ends. Excluded. Default: the end of the list.step— how many positions to move between elements. Default:1.
stop is the index where the slice stops before taking an element, which is why [1:4] includes indexes 1, 2 and 3 but not 4.
A slice always returns a new list. A negative step walks backwards: numbers[::-1] reverses the list.
Coming from JavaScript? items[start:stop] is .slice(start, stop). Python adds a step: items[::2] has no direct array method, and items[::-1] reverses without mutating.
Slice with start and stop
Create numbers = [10, 20, 30, 40, 50] and print the slice from index 1 (included) to index 4 (excluded).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Slice from the beginning
Create numbers = [10, 20, 30, 40, 50] and print the slice from the beginning up to index 3 (excluded).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Slice to the end
Create numbers = [10, 20, 30, 40, 50] and print the slice from index 3 to the end of the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Reverse with a negative step
Create numbers = [10, 20, 30, 40, 50] and print the list in reverse order using a slice with step -1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Every second element
Create numbers = [10, 20, 30, 40, 50] and print every second element starting at index 0, using a slice with step 2.
Print exactly:
Create a free account to save your progress and unlock chapter 2.