In Python, list slicing lets you extract portions of a list using the syntax:
list[start:stop:step]
Components
start→ index where the slice begins (inclusive).stop→ index where the slice ends (exclusive).step→ interval between indices (default is1).
Start = 1 → begin at index
1(the second element, which is20).Stop = 4 → go up to, but not including, index
4.So you get elements at indices
1,2, and3→20, 30, 40.
Python slicing always excludes the stop index. That’s why 50 (at index 4) isn’t included.
print(numbers[::2])
Start = empty → defaults to the beginning of the list (
index 0).Stop = empty → defaults to the end of the list.
Step = 2 → take every second element.
So Python picks indices 0, 2, 4, ... until the end
myList = [1, 2, 3, 4, 5] print(myList[0:6:2])
Start = 0 → begin at index 0 (1).
Stop = 6 → go up to, but not including, index 6.
Step = 2 → take every second element.
Notice that even though you wrote stop = 6, your list only goes up to index 4. Python slicing doesn’t throw an error — it just stops at the end of the list. That’s why you still get [1, 3, 5].
The range() function in Python generates a sequence of integers, starting from a given start (default 0), stopping before a given stop, and incrementing by a given step (default 1). It’s most often used in loops to control iteration.
range(start, stop, step)
start → optional, default 0. First number in the sequence.
stop → required. Sequence ends before this number.
step → optional, default 1. Difference between consecutive numbers.
Range function is immutable.
>>> for i in range(5): ... print(i) ... 0 1 2 3 4 >>>
>>> myList = [1,2,3,4] ... myList.append(5) ... print(myList) ... [1, 2, 3, 4, 5] >>>
In Python, lists have several useful methods for adding and removing elements. Let’s look at insert(), remove(), and pop() side by side:
numbers = [10, 20, 30] numbers.insert(1, 15) # insert 15 at index 1 print(numbers) # [10, 15, 20, 30]
len(myList) is now 0.b = a.copy() → makes a shallow copy of a.
Now
bhas its own separate list[1,2,3,4,5].