Python Tutorial
Python Join Lists
Join two lists with +, a loop, or extend().
Join with +
Create a new list from two lists.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)extend()
Add list2 onto list1 in place.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)📘 Real-World Deep Dive
Joining a list with a separator is a daily operation but easy to do badly (<code>+</code> in a loop vs. <code>str.join</code> once). Knowing the canonical patterns makes output code short and fast.
Real-Life Scenario
Compose a few different "join-like" outputs: CSV row, SQL <code>IN (...)</code>, shell command, and multi-line block — all from the same list of identifiers.
Real-Life Example
import shlex
ids = ["user-1", "user-2", "user-3"]
csv = ",".join(ids)
sql_in = ", ".join(f"'{x.replace(chr(39), chr(39)*2)}'" for x in ids)
shell = " ".join(shlex.quote(x) for x in ids)
block = "\n".join(f" {x}" for x in ids)
print("csv :", csv)
print("sql :", f"SELECT * FROM users WHERE id IN ({sql_in});")
print("sh :", shell)
print("block:")
print(block)Expected Output
csv : user-1,user-2,user-3
sql : SELECT * FROM users WHERE id IN ('user-1', 'user-2', 'user-3');
sh : 'user-1' 'user-2' 'user-3'
block:
user-1
user-2
user-3Common mistakes
- Concatenating strings in a loop with
+=is O(n²); use"".join(xs). - Naive CSV join misses quoting/escaping — use the
csvmodule for serious work. shlex.quoteis the safe way to embed filenames into shell commands; don't roll your own.
🚀 Performance & Best Practices
"".join(parts)is C-fast for thousands of fragments;reduce(operator.add, parts)is not.- Use
io.StringIOwhen each fragment needs non-trivial formatting. - Pre-build the join template to skip
str.formatoverhead.
🧪 Try It Yourself
- Add support for multi-character separators per join style.
- Implement
join_with_and(items)returning"a, b, and c". - For SQL, parse into
sqlalchemy.sql.quoted_nameinstead of hand-rolling.