What will the following Python code output?
What will the following Python code output?
arr = [1, 3, 5, 7, 9]
res = arr[::-1][::2]
print(res)
Options:
[9, 7, 5, 3, 1]
[9, 5, 1]
[1, 5, 9]
[3, 7, 9]
Answer :
Step 1: Understanding arr[::-1]
The slicing syntax [::-1] reverses the array.
- Original array: [1, 3, 5, 7, 9]
- Reversed array: [9, 7, 5, 3, 1]
So after the first slice (arr[::-1]), the array becomes:
[9, 7, 5, 3, 1]
Step 2: Understanding [::2]
Now, we take the reversed array and apply the slicing [::2].
The slicing [::2] means:
- Start from the beginning of the array.
- Take every second element (step size = 2).
For the reversed array [9, 7, 5, 3, 1]:
- First element: 9 (index 0)
- Skip one element (7) and take 5 (index 2).
- Skip one more element (3) and take 1 (index 4).
Result after [::2]: [9, 5, 1]
Step 3: Storing the Result in res
The final result of the combined slicing is stored in res:
res = [9, 5, 1]
Step 4: Printing the Result
When you print res, the output is:
Key Points:
- [::-1] reverses the array.
- [::2] selects every second element from the reversed array.
- Combining slices gives the desired result [9, 5, 1].
0 Comments:
Post a Comment