+ 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! 🙏
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]
+ 3
Khushal, [1] isn't a[1], it's a list containing only the integer 1. He replaces [2, 3, 4, 5] with [1]
+ 3
yea @Chris, that's exactly what i said
+ 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]
+ 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]
+ 2
try a[2:4] = [5]
+ 2
Thank you for all of your help guys! Now I understand everything perfectly 😀