+ 2

Why is the output [1,1]?

a = [1,2,3,4,5] a[1:5] = [1] print(a) Output [1,1] I’ve been playing around with this code for one hour. I’d be grateful for any help! 🙏

19th Mar 2018, 5:25 PM
Yohann
7 Respuestas
+ 5
a[1:5] means select list items from 1 to 5 and you are assigning to 1 as a[0] is already 1 the output is [1,1]
19th Mar 2018, 5:31 PM
kaliki chandu
kaliki chandu - avatar
+ 3
Khushal, [1] isn't a[1], it's a list containing only the integer 1. He replaces [2, 3, 4, 5] with [1]
20th Mar 2018, 1:44 AM
Chris
Chris - avatar
+ 3
yea @Chris, that's exactly what i said
20th Mar 2018, 3:15 AM
Khushal Sahni
Khushal Sahni - avatar
+ 2
Well it's very simple, you know index of the first element is 0 so when you use the command a[1:5] = [1] you are assigning all the values from index 1( second element) to the index before 5 i.e. 4th ( last element) to [1] , but there is already a 1 at the 0th index so now you have two 1s in your list and the output is [1, 1]
19th Mar 2018, 5:33 PM
Khushal Sahni
Khushal Sahni - avatar
+ 2
a[start:end+1] = value a = [1,2,3,4,5] when we assign a[1:5] = [1] this will remove all value from a[1] to a[4] and adds 1 at index 1 so a = [1,1]
19th Mar 2018, 5:33 PM
Dinesh Banjara
Dinesh Banjara - avatar
+ 2
try a[2:4] = [5]
19th Mar 2018, 5:35 PM
Dinesh Banjara
Dinesh Banjara - avatar
+ 2
Thank you for all of your help guys! Now I understand everything perfectly 😀
19th Mar 2018, 6:45 PM
Yohann