+ 1

Why output is b 2 and not b 1 ?

try: s = ['a','c'] n = [0,2] s[1:1] = 'b' n[1:1] = 1 except: pass print(s[1], n[1])

6th Mar 2020, 12:07 PM
Peter Parker
Peter Parker - avatar
2 ответов
+ 2
because string is a sequence type, and integer is not. You cannot insert not sequence type in the list (using slicing method). try: s = ['a','c'] s is list of two elements 'a', 'c' n = [0,2] n is list of two elements 0,2 s[1:1] = 'b' insert string 'b' to position with index #1 string 'b' is a sequence type, it has 1 element = ['b'], so it can be inserted to s without any problem s now contains 3 elements: ['a', 'b', 'c'] n[1:1] = 1 here exception is thrown, as 1 is integer (not a sequence type) and can't be inserted list n remains unchanged it contains [0, 2] except: pass pass do nothing (exception doesn't printed, as try{}except presents ) print(s[1], n[1]) prints second elements of the ['a', 'b', 'c'] and [0, 2] if you want to get output b 1, you should replace line n[1:1] = 1 with line n[1:1] = [1]
6th Mar 2020, 12:55 PM
andriy kan
andriy kan - avatar
+ 1
'b', although only one letter, is an iterable. 1, on the other hand, is not. The slicing method that is used in line 3 and 4 needs an iterable on the right side, so in line you get an error.
6th Mar 2020, 12:54 PM
HonFu
HonFu - avatar