+ 1

Help with this Python output!

Input: a = [1, 2, 3, 4, 5] a[1:5] = [1] print(a) Output: [1, 1] This may be a stupid question and I may be missing something really obvious but why is this this output here?

15th May 2018, 12:12 PM
stephanie
stephanie - avatar
5 Antworten
+ 4
In your case print(a[1:5]) outputs [2,3,4,5], which are from the second to the fifth character in a list. So a[1:5] = [1] replaces all characters from the second to the fifth one with a 1, but it still leaves the first character on its position. So [1, 1] is the first character of old list + the character with which you replaced second to fifth element.
15th May 2018, 12:57 PM
Tim Thuma
Tim Thuma - avatar
+ 3
hi, it looks that a[1:5]=[1] just replace items from "2" to "5" with "1". So the output consists of the original "1" and the new one "1"
15th May 2018, 12:38 PM
Andrei
15th May 2018, 1:04 PM
cyk
cyk - avatar
+ 1
You should learn list operation a = [1, 2, 3, 4, 5] is a list a list index start from 0, a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 a[1:5] = [1] --> you're slicing list and assigning value = 1, except a[0] so print(a) ---> [1, 1]
15th May 2018, 1:02 PM
Fery Ardiansyah
Fery Ardiansyah - avatar
+ 1
Ooo okay lol I see now whoops thank you
15th May 2018, 3:25 PM
stephanie
stephanie - avatar