What Is the Output of This Python Code?
Question:
x = [1, 2, 3]
print(x[1:])
Options:
A) [1, 2, 3]
B) [1, 2]
C) [2, 3]
D) Error
Correct answer :
C) [2, 3]
Explanation :
First we create a list:
x = [1, 2, 3]
The list contains three elements .
Index positions:
Index : 0 1 2
Value : 1 2 3
Step 1 - List slicing
x[1:]
This is called list slicing.
Syntax :
list[start : end]
- Start → index where slicing begins
- end → index where slicing stops (not included)
If end is not given python takes elements until end of the list.
Step 2 - Applying the slice
x[1:]
Start form index 1.
Index 1 → value 2
Index 2 → value 3
So the result becomes.
[2, 3]
Final output :
[2, 3]
Key points :
List slicing is used to extract a part of the list.
Examples :
x[0:2] → [1, 2]
x[:2] → [1, 2]
x[1:] → [2, 3]
Practice daily Python coding challenges to improve your programming and logical thinking skills.
Happy coding ❤️

No comments:
Post a Comment