- 2

About python MCQ

What is the output of this code? a=[1,2,3,4,5] a[1,5] = [1] Print(a) But how the output is [1,1]?

14th Oct 2022, 2:57 AM
Mustakim Rahman
Mustakim Rahman - avatar
4 Answers
+ 7
Mustakim Rahman , this should be the correct code, may be a typo has happend to you: ... a[1:5] = [1] ... this is called a *slice assignment on the left hand side of an expression*. it means that in list *a* the indexes between *1* and *5* are replaced by the value of [1] (has to be an iterable). so the result is: [1, 1]
14th Oct 2022, 10:40 AM
Lothar
Lothar - avatar
+ 2
Mustakim Rahman a[1:5] means 2,3,4,5 index in python starts at 0. The values (2,3,4,5) gets replaced with 1 leaving [1,1] as answer
14th Oct 2022, 1:26 PM
Sandeep
Sandeep - avatar
+ 1
The output is runtime error. In Python this is invalid. a[1,5] You cannot use a tuple as index.
14th Oct 2022, 4:00 AM
Tibor Santa
Tibor Santa - avatar
+ 1
But #Lother a[1:5] means a=1,2,3,4 Why just [1,1]?
14th Oct 2022, 11:07 AM
Mustakim Rahman
Mustakim Rahman - avatar