+ 2
Why string-element of list could be modified but integer-element not? Python challenge question.
try: s = [“a”, “c”] n = [0, 2] s[1:1] = “b” n[1:1] = 1 except: pass print(s[1], n[1]) Output: b 2 Why modifying string-element of list “s” worked but same thing did not work to replacing in list “n” which is integer-element? Thanks in advance,
11 ответов
+ 4
Tricky one!
`n[1:1]` selects a sub-list, so you will need to assign a list to it, not a single number!
It works for strings, because any string is also a list at the same time.
Try running this:
x = [0,2]
x[1:1] = [1]
print(x)
c =["a","b"]
c[1:1] = "oh!"
print(c)
You will see that now, integer assignment works, and in the string case, your list actually has 3 new elements because "oh!" was split!
+ 4
Schindlabua That's great, but for the x list, it becomes [0,1,2] instead of [0,1], that means we are inserting a new element instead of modifying an existing one. And as Sercan said, to modify by x[1] = 1 way was wrong, I'm confused here : )
+ 3
I cannot explain how, but it works this way ...
s[1] = "b"
n[1] = 1
+ 3
Sercan Yes I understand, and I also want to hear Schindlabua's opinion about this, no worries he is a moderator, he knows better what to do for something like this : )
+ 2
Ipang Not sure what you mean exactly! If you run the code it says "b 2", just like Sercan said in the description. The n[1:1] throws but we ignore the exception, so the quiz did everything accurately I think :)
Edit: Like, the quizzer only wants to know what the second element is, he does not care about whether we added new elements or modified existing ones.
+ 1
Ipang thank you for your answer, i also chose same answer in challenge, but it was wrong. Afterwards i typed the code and run it, output: b 2 , i could not get it
+ 1
Schindlabua thank you so much, it is clear now
+ 1
Ipang Ah that's just the range selector being what it is. `x[1:1]` actually selects zero elements, so you aren't modifying any, and you're just inserting at position 1.
I agree the code is a bit hard to read, I had to run it to see what's happening.
+ 1
Ipang i have tried x[1] = 1 instead of x[1:1] = 1 and it worked as we expected in the first place
+ 1
Schindlabua Big Thanks for more explanation, yet one more doubt still lingers, is it possible that quiz was faulty? I mean, assigning a new value to a certain element by referring the index is how we do it, if we were modifying a single element, but the quiz says it's wrong, I wonder that : )
+ 1
Schindlabua Well in that case I suppose you're right, since I don't know the quiz instructions, I don't even play challenges : )
But I stand by my point, if it was to modify a list element I would do list[index] = new_value, which was declared wrong in the quiz, according to Sercan. I trust your analysis on this matter nonetheless 👍