+ 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'
4 Answers
+ 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.
+ 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â)
+ 3
Thank you John.
+ 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']