Explanation:
Line 1: Creating a List
x = [1, 2, 3, 4]
A variable named x is created.
x stores a list containing four numbers.
The elements and their indexes are:
Index Value
0 1
1 2
2 3
3 4
Line 2: Printing a Slice of the List
print(x[:2])
print() displays the result on the screen.
x[:2] is a list slice.
Understanding the Slice x[:2]
The slicing syntax is:
list[start:end]
Where:
start = included
end = excluded
For:
x[:2]
Python treats it as:
x[0:2]
This means:
Start at index 0
Stop before index 2
Elements Selected
Index : 0 1 2 3
Value : 1 2 3 4
↑ ↑
Selected elements:
[1, 2]
Output
[1, 2]

0 Comments:
Post a Comment