What Is the Output of This Python Code?
Question :
x = [1, 2, 3, 4]
print(x[-1])
Options :
A) 1
B) 3
C) 4
D) Error
Correct Answer :
C) 4
Explanation :
First we create a list :
x = [1, 2, 3, 4]
The list contains 4 elements
Index positions :
Index : 0 1 2 3
Value : 1 2 3 4
Step 1 - Negative indexing
In python we can access elements form the end of the list using negative indexing.
-1 → last element
-2 → second last element
-3 → third last element
So the list looks like this :
Index : 0 1 2 3
Value : 1 2 3 4
Negative Index :
-4 -3 -2 -1
Step 2 - Accessing the element
print(x[-1])
-1 refers to the last element of the list.
So python prints :
4
output :
4
key points :
Negative indexing allows accessing list elements form the end of the list.
Example :
x[-1] → last element
x[-2] → second last element
Practice daily Python coding challenges to improve your programming and logical thinking skills.
Happy coding ❤️

No comments:
Post a Comment