Computer Science
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 = "")
Answer
234566
Working
arr
is initialised as a list with elements [1, 2, 3, 4, 5, 6].for
loop iterates over the indices from 1 to 5. For each indexi
, it assigns the value ofarr[i]
toarr[i - 1]
, effectively shifting each element one position to the left. After this loop, the listarr
becomes[2, 3, 4, 5, 6, 6]
.- Second for loop iterates over the indices from 0 to 5 and prints each element of the list
arr
without newline characters because ofend=""
parameter. Then it prints the elements of the modified listarr
, resulting in234566
.
Related Questions
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 ?
a = [1, 2, 3, 4, 5] print(a[3:0:-1])
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( )
Find the errors. State reasons.
t = (1, "a", 9.2) t[0] = 6