+ 1
What is the output of this code? (Please explain)
A =[x for x in range[ (4)]. Print(sum(a[1::-2]+ a[::-3]))
2 Answers
+ 5
a = [0,1,2,3]
>>>a[1::-2]
[1]
The reason it returns [1] is because out of range slice indexes are handled gracefully when used for slicing. So, it starts from a[1] but it doesn't have stopping value and step is -2 which is out of range.
>>>a[::-3]
[3,0]
Since it has a negative step value, it includes elements starting from backwards with a step of 3.
>>>[1] + [0,3]
[1,0,3]
>>> sum([0,1,3])
4
The sum() takes a list and sum all values of this.
+ 2
Thank you, Simba đ„ș