+ 1

try + list question

Why n[1:1] = 1 has NOT been changed and it is still 2!?? Why s[1:1] = 'b' can be changed but (n[1:1] = 1) cannot? try: s = ['a', 'c'] n = [0, 2] s[1:1] = 'b' n[1:1] = 1 except: pass print(s[1], n[1]) Output is: 'b 2'

3rd Jul 2018, 4:47 PM
Dolan
Dolan - avatar
4 Antworten
+ 5
Your [1:1] forms a slice. This is not a element in the list. Your 'b' works because strings act like a list. n[1:1] = [1] would work.
3rd Jul 2018, 9:48 PM
John Wells
John Wells - avatar
+ 4
Thanks again. After you description, I tried it with square brackets [1] and it worked. and also for strings which will be seperated letter by letter as a list item (‘bd’)
4th Jul 2018, 2:05 PM
Dolan
Dolan - avatar
+ 3
Thank you John.
4th Jul 2018, 7:45 AM
Dolan
Dolan - avatar
+ 3
Note: if you print your list, you are inserting elements. s = ['a', 'c'] s[1:1] = 'bd' print(s) #outputs #['a', 'b', 'd', 'c']
4th Jul 2018, 1:53 PM
John Wells
John Wells - avatar