Why list slicing showing differences in string list and number list? | SoloLearn: Learn to code for FREE!

+4

Why list slicing showing differences in string list and number list?

Based upon the code below , i don't understand * if a list is there say s, then is s[1:1] work * in code, why s[1:1] which is a list of strings changes but not n[1:1] which is list of numbers ? https://code.sololearn.com/cM64cXV2LZ6l/?ref=app

5/3/2019 3:11:57 AM

Suzan

6 Answers

New Answer

+3

Sujata You can only assign iterables when assigning in slice notation. string is an iterable so s[1:1] = 'b' will add a new item but int is not itetable, so you cannot add int to list using slice notation you should do n[1:1] = [2] but strange it should have given error for direct int assignment

+5

The problem with your code is that you missed []. You have to assign a list or iterable to a list slice. You should do something like this: s = ['a', 'c'] n = [0, 2] s[1:1] = ['b'] n[1:1] = [3] print(s, n)

+4

Kartik Krishnan and ~ swim ~ thanks a lot 😀 I understood where i had gone wrong.

+2

~ swim ~ Yes it should have given error but Sujata used try and except...

+2

Kartik Krishnan Oh yes, I didn't see try except at all :)

0