Code Explanation:
Line 1: Creating a List
x = [1, 2, 3, 4]
x is a variable.
[1, 2, 3, 4] is a list containing 4 elements.
The elements are stored in the following positions (indexes):
Index Value
0 1
1 2
2 3
3 4
Python also supports negative indexing:
Negative Index Value
-1 4
-2 3
-3 2
-4 1
Line 2: Accessing an Element
print(x[-2])
Step 1
x[-2] means:
Start counting from the end of the list.
-1 refers to the last element → 4
-2 refers to the second-last element → 3
So:
x[-2]
becomes:
3
Step 2
print() displays the value on the screen.
print(3)
Output
3

0 Comments:
Post a Comment