DSA Strings in Python
A string is an immutable sequence of characters. Immutable means the characters cannot be changed in place, so edits build a new string.
Reading characters
Indexing picks one character by position. Slicing copies a run of characters.
word = "python"
print("first:", word[0])
print("last:", word[-1])
print("slice:", word[1:4])Strings cannot change in place
This code builds a new string instead of editing the old one. The old string stays untouched.
word = "cat"
new_word = "b" + word[1:]
print("old:", word)
print("new:", new_word)Counting the copies
Each concatenation copies every character built so far. Three joins here copy 3, then 7, then 12 characters.
parts = ["ab", "cde", "fghi"]
built = ""
copies = 0
for part in parts:
built = built + part
copies += len(built)
print("built:", built, "| copied so far:", copies)Example
def build_concat(words):
result = ""
copies = 0
for word in words:
result = result + word
copies += len(result)
return result, copies
def build_join(words):
result = "".join(words)
copies = len(result)
return result, copies
words = ["the", "quick", "brown", "fox"]
joined_concat, concat_copies = build_concat(words)
joined_join, join_copies = build_join(words)
print("concat result:", joined_concat)
print("concat characters copied:", concat_copies)
print("join result:", joined_join)
print("join characters copied:", join_copies)Key points
- A string holds characters in order, like a list holds values
- Immutable means no character can be replaced in place
- Indexing reads one character in one step
- Joining a list of words builds one string with one pass over the characters
- Repeated concatenation copies the whole string again on every step
In this example, both builders join the same four words with no spaces. Concatenation copies the growing string on every step. Its copies add up to 3 plus 8 plus 13 plus 16, which is 40. Join copies each character once, which is 16. The results match, and the copy counts prove why join is the cheaper builder.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
Why does building a long string with repeated + cost more than join?