› Forums › Python › ✅ Understanding the + (Concatenation) Operator in Python Lists (Phonebook Example)
- This topic is empty.
-
AuthorPosts
-
January 26, 2026 at 8:05 pm #5979
Initial Code (Example)
class FileHandler(): def __init__(self, filename): self.__filename = filename def load_file(self): # ... def save_file(self, phonebook: dict): with open(self.__filename, "w") as f: for name, numbers in phonebook.items(): line = [name] + numbers f.write(";".join(line) + "\n")
✅ Q&A
Q1) What does the
+operator do in this line?line = [name] + numbers✅ Answer:
Here,+is used for list concatenation, meaning it joins two lists into one list.
Q2) Why is
[name]written in square brackets?✅ Answer:
Because[name]turns the name into a list containing one item.
Example:name = "Amit" [name] # becomes ["Amit"]This is required because Python can only concatenate list + list.
Q3) What type of value should
numbersbe?✅ Answer:
numbersmust be a list of strings, like:numbers = ["9876543210", "9123456789"]So it can be combined with
[name].
Q4) What happens after concatenation?
✅ Answer:
Suppose:name = "Amit" numbers = ["9876543210", "9123456789"]Then:
line = [name] + numbersbecomes:
["Amit", "9876543210", "9123456789"]So the name and phone numbers become one single list.
Q5) Why is
linecreated this way before writing to the file?✅ Answer:
Because the next line uses:";".join(line)join()works only on one list of strings, so we create a combined list first.
Q6) What does this line do?
f.write(";".join(line) + "\n")✅ Answer:
It writes the data into the file in this format:Amit;9876543210;9123456789";".join(line)joins list items with;+ "\n"adds a new line after each contact
Q7) Can we concatenate a list with a string?
✅ Answer:
❌ No. Python will throw an error.Example (Wrong):
["Amit"] + "9876543210"✅ Correct way:
["Amit"] + ["9876543210"]
Q8) What is the practical use of this
+operator in file saving?✅ Answer:
It makes the file clean and structured by storing:Name + all phone numbers in one row, separated by semicolons.
This is very useful for saving phonebook/contact data in a readable format.
If you want, I can also create the matching
load_file()function that reads this exact format back into a dictionary ✅ -
AuthorPosts
- You must be logged in to reply to this topic.

