Computer Science
Predict the output of the following code snippet ?
a = [1, 2, 3, 4, 5]
print(a[3:0:-1])
Python
Python List Manipulation
2 Likes
Answer
[4, 3, 2]
Working
The slicing notation a[start:stop:step]
extracts a portion of the list from index start
to stop-1
with a specified step. In the slicing part a[3:0:-1]
:
start
is 3, which corresponds to the element with value 4.stop
is 0, but as element at stop index is excluded so slicing goes up to index 1.step
is -1, indicating that we want to step backward through the list.
Putting it together:
a[3:0:-1]
This extracts elements from index 3 to (0+1) in reverse order with a step of -1.
The output of the code will be:
[4, 3, 2]
Answered By
1 Like
Related Questions
What will be the output produced by following code fragments?
x = "hello world" print (x[:2], x[:-2], x[-2:]) print (x[6], x[2:4]) print (x[2:-3], x[-4:-2])
Write a short Python code segment that adds up the lengths of all the words in a list and then prints the average (mean) length.
Predict the output of the following code snippet?
arr = [1, 2, 3, 4, 5, 6] for i in range(1, 6): arr[i - 1] = arr[i] for i in range(0, 6): print(arr[i], end = "")
Predict the output of the following code snippet ?
Numbers = [9, 18, 27, 36] for Num in Numbers : for N in range(1, Num % 8) : print(N, "#", end=" ") print( )