Join instead of += in a loop
Both ways give the same text. Only the cost differs, and the difference grows with the size of the input.
A string can never be changed after it is created: every "change" builds a new string. Knowing this explains why s[0] = "J" fails, why joining pieces beats += in a loop, why you should compare strings with == and never is, and when io.StringIO is the right buffer.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Build the string "01234" once with += in a loop and once by collecting pieces in a list and joining them. Print both and whether they are equal.
Use io.StringIO and print(..., file=buffer) to collect three lines row 0, row 1, row 2 and then print the collected text.
Make two equal strings using "he" + "llo" and sys.intern("hel" + "lo") and show that comparing with == is True.
Explain it without notes
What does it mean that strings are immutable, and what happens when you write s = s + "!"?
Why is "".join(pieces) preferred over += in a loop?
Why is a == b the right way to compare strings, and what can a is b give?
When would you use io.StringIO?
Expected output
'to be or not to be '
'to be or not to be'
same text: True
0,1,4,9,16