Introduction
In Python, joining a database intends combining its elements into a azygous string, utilizing a separator to spot betwixt each element. The modular instrumentality for this is the drawstring join() method, which takes an iterable (such arsenic a list) and returns 1 string. This cognition is useful whenever you request to move a database of values into text, for illustration redeeming a database of names arsenic a comma-separated statement successful a record aliases building a condemnation from a database of words.
In this tutorial, you will study the different ways to subordinate a Python database and harvester lists successful Python. You will commencement pinch the join() method for joining a database of strings, past screen really to subordinate a database of integers and mixed information types, really to grip None values and nested lists, really to concatenate 2 aliases much lists pinch the + operator, list.extend(), the * unpacking operator, and itertools.chain(), and really the methods comparison successful performance. You will besides spot why join() lives connected the drawstring people alternatively than the database class, and which modern alternatives Python now offers.
Key Takeaways:
- The drawstring join() method is the modular and fastest measurement to subordinate a database of strings into 1 drawstring pinch a chosen separator.
- The syntax is separator.join(iterable): the separator is the drawstring you telephone join() on, and the database is passed arsenic the argument.
- join() useful only connected strings, truthful joining a database that contains integers, None, aliases different types raises a TypeError.
- To subordinate a database of integers, person each point to a drawstring first pinch map(str, list) aliases a database comprehension.
- To skip None values earlier joining, usage a generator look specified arsenic ",".join(x for x successful items if x is not None).
- Use the + usability aliases list.extend() to concatenate 2 lists into a caller list, and the * unpacking usability (Python 3.5+) for a concise merge.
- For joining galore aliases very ample lists, itertools.chain() avoids building intermediate lists and uses little memory.
- Building a drawstring pinch repeated + successful a loop runs successful O(n^2) time, while join() runs successful O(n); successful a benchmark connected 100,000 items, join() was astir 8 times faster.
- join() is simply a drawstring method (not a database method) because it useful pinch immoderate iterable and ever returns a string.
Join a Python database of strings pinch join()
We tin usage the Python string join() method to subordinate a database of strings. The method is called connected the separator drawstring and takes the iterable arsenic its argument, truthful the wide shape is separator.join(iterable). Because a database is an iterable, we tin walk a database directly. The database should incorporate only strings; if you effort to subordinate a database of integers you will get a TypeError, which the statement beneath explains really to fix.
Let’s look astatine a short illustration that joins a database of vowels into a comma-separated string:
vowels = ["a", "e", "i", "o", "u"] vowels_csv = ",".join(vowels) print("Vowels are =", vowels_csv)Output
Vowels are = a,e,i,o,uThe separator tin beryllium immoderate string, not conscionable a comma. The adjacent conception shows really to subordinate pinch a space, a newline, aliases immoderate civilization separator.
Join a database pinch a comma, space, newline, aliases civilization separator
Because the separator is conscionable the drawstring you telephone join() on, you tin alteration the output format simply by changing that string. A abstraction joins words into a sentence, "\n" puts each point connected its ain line, and immoderate different drawstring useful arsenic a civilization separator.
The pursuing illustration joins the aforesaid database 3 different ways:
words = ["Python", "is", "awesome"] print(" ".join(words)) # abstraction separator print("\n".join(words)) # newline separator print(" -> ".join(words)) # civilization separatorOutput
Python is awesome Python is awesome Python -> is -> awesomeThe newline subordinate is particularly useful erstwhile penning a database to a matter file, wherever each constituent should look connected its ain line.
Join an quiet list
Joining an quiet database is safe and simply returns an quiet string, truthful you do not request a typical cheque for it.
print(repr("".join([]))) print(repr(",".join([])))Output
'' ''This predictable behaviour is convenient erstwhile the database mightiness beryllium quiet astatine runtime, since the telephone will not raise an error.
Join a database of integers successful Python
A database of integers cannot beryllium passed to join() directly, because join() only accepts strings. Attempting it raises TypeError: series point 0: expected str instance, int found. The hole is to person each constituent to a drawstring first, and location are 2 communal ways to do that.
Using map() pinch join()
The map() usability applies str to each constituent of the list, producing drawstring versions that join() tin accept. This is concise and sounds good for elemental conversions, and you tin study much astir it successful the tutorial connected the Python map() function.
int_list = [1, 2, 3, 4, 5] joined_str = ",".join(map(str, int_list)) print("Joined string:", joined_str)Output
Joined string: 1,2,3,4,5Using a database comprehension for type conversion
A list comprehension does the aforesaid conversion and is simply a bully prime erstwhile you want to toggle shape each point further, for illustration formatting numbers while converting them.
int_list = [1, 2, 3, 4, 5] joined_str = ",".join([str(element) for constituent in int_list]) print("Joined string:", joined_str)Output
Joined string: 1,2,3,4,5Both approaches are correct; map(str, ...) is somewhat faster and much compact, while the comprehension is easier to widen erstwhile each constituent needs other formatting.
Join a database pinch mixed information types
When a database mixes strings pinch different types, join() raises a TypeError because it expects each constituent to already beryllium a string. The database ['Java', 'Python', 1] is simply a emblematic example: the integer 1 causes the error.
names = ['Java', 'Python', 1] single_str = ','.join(names) print(single_str)This raises the pursuing error:
Output
TypeError: series point 2: expected str instance, int foundThe instruction is that a database containing aggregate information types cannot beryllium mixed into a azygous drawstring pinch join() directly; you must person the non-string items first, arsenic the adjacent 2 sections show.
Handling None values successful a database earlier joining
A None worth triggers the aforesaid TypeError, truthful you request to determine whether to driblet the None values aliases person them to text. To driblet them, select the database pinch a generator look earlier joining.
items = ["a", None, "b"] result = ",".join(x for x in items if x is not None) print(result)Output
a,bIf you would alternatively support a placeholder for the missing value, person each constituent pinch str() instead, which turns None into the matter "None".
items = ["a", None, "b"] result = ",".join(str(x) for x in items) print(result)Output
a,None,bChoose the filtering attack erstwhile missing values should disappear, and the conversion attack erstwhile their position matters.
Filtering non-string items earlier joining
The aforesaid generator-expression shape lets you support only the items you want, for illustration joining conscionable the drawstring elements of a mixed database and ignoring everything else.
mixed = ['Java', 'Python', 1, None, 'Go'] result = ",".join(x for x in mixed if isinstance(x, str)) print(result)Output
Java,Python,GoUsing isinstance(x, str) keeps the strings and silently skips the integer and the None, which is useful erstwhile a database whitethorn incorporate unpredictable types.
Join a nested database successful Python
A nested database (a database of lists) cannot beryllium joined straight either, because its elements are lists alternatively than strings. You first request to flatten it into a azygous series of strings, and location are 2 cleanable ways to do that.
Flattening a nested database pinch a database comprehension
A nested database comprehension walks each sublist and past each item, producing a level database of strings that join() tin accept.
nested = [["a", "b"], ["c", "d"]] flat = [item for sub in nested for point in sub] print(",".join(flat))Output
a,b,c,dUsing itertools.chain.from_iterable()
For larger nested lists, itertools.chain.from_iterable() flattens the building lazily without building an intermediate list, which is much representation efficient.
import itertools nested = [["a", "b"], ["c", "d"]] print(",".join(itertools.chain.from_iterable(nested)))Output
a,b,c,dBoth nutrient the aforesaid result; scope for chain.from_iterable() erstwhile the nested information is ample aliases streamed, and the comprehension erstwhile readability matters most.
What happens erstwhile you walk a drawstring to join()
A communal constituent of disorder is calling join() connected a azygous drawstring alternatively of a list. Because a drawstring is itself an iterable of characters, join() iterates complete its individual characters and inserts the separator betwixt each one.
message = "Hello ".join("World") print(message)Output
WHello oHello rHello lHello dAs the output shows, this does not nutrient "Hello World". Because 'World' is simply a drawstring and strings are iterables of characters, join() inserts 'Hello ' betwixt each individual characteristic of 'World', not betwixt 2 full words. To harvester 2 full strings, usage concatenation pinch + aliases an f-string alternatively of join().
Why join() is simply a drawstring method and not a database method
A mobility galore Python developers inquire is why join() belongs to the drawstring people and not to the database class. Wouldn’t the syntax beneath beryllium easier to remember?
vowels_csv = vowels.join(",")There is simply a well-known StackOverflow discussion astir this. The halfway reasoning is that join() useful pinch immoderate iterable, not conscionable lists, and it ever returns a string. If join() were a method connected each iterable, the aforesaid logic would person to beryllium duplicated crossed lists, tuples, sets, generators, and more. Placing it connected the drawstring people alternatively intends a azygous implementation handles each iterable, and the separator is people the drawstring you telephone the method on.
The charismatic Python archiving describes str.join() arsenic follows: “Return a drawstring which is the concatenation of the strings successful iterable.” It besides notes that “a TypeError will beryllium raised if location are immoderate non-string values successful iterable, including bytes objects.” This is precisely the behaviour you saw successful the integer and mixed-type examples above, and it confirms why the method is defined wherever it is.
Concatenate 2 aliases much lists successful Python
Joining for drawstring output is different from concatenating lists into a caller list. When your extremity is simply a mixed database alternatively than a string, Python gives you respective options, each pinch different capacity characteristics. You tin publication much successful the tutorial connected concatenating lists successful Python.
Using the + operator
The + usability creates a caller database by joining 2 existing lists, which is the simplest attack for a elemental merge of mini lists.
list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined)Output
[1, 2, 3, 4, 5, 6]Using list.extend()
The list.extend() method adds each constituent of 1 database onto different successful place, without creating a caller list. It is the correct prime erstwhile you are increasing an existing list, and it is covered alongside different list-growing methods successful the tutorial connected adding elements to a database successful Python.
combined = [1, 2, 3] combined.extend([4, 5, 6]) print(combined)Output
[1, 2, 3, 4, 5, 6]Using the * unpacking usability (Python 3.5+)
Since Python 3.5, the * unpacking usability tin beryllium utilized wrong database literals to dispersed respective lists into a caller list. It is concise and useful pinch much than 2 lists astatine once.
list1 = [1, 2, 3] list2 = [4, 5, 6] combined = [*list1, *list2] print(combined)Output
[1, 2, 3, 4, 5, 6]Using itertools.chain() for memory-efficient joins
For merging galore lists, aliases very ample ones, itertools.chain() returns an iterator that yields elements from each database successful move without building intermediate lists, which keeps representation usage low.
import itertools list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list(itertools.chain(list1, list2)) print(combined)Output
[1, 2, 3, 4, 5, 6]Joining 2 lists without duplicates
If you request a mixed database pinch copy values removed while preserving order, concatenate the lists and walk the consequence to dict.fromkeys(), which keeps only the first occurrence of each value.
list1 = [1, 2, 3] list2 = [3, 4, 5] combined = list(dict.fromkeys(list1 + list2)) print(combined)Output
[1, 2, 3, 4, 5]Using dict.fromkeys() preserves insertion bid (guaranteed since Python 3.7), which a plain set() would not.
Split a drawstring backmost into a database pinch split()
The split() method is the inverse of joining: it breaks a drawstring into a database utilizing a delimiter. This is useful erstwhile you person joined a database into a drawstring and later request the original database back.
names = ['Java', 'Python', 'Go'] delimiter = ',' single_str = delimiter.join(names) print('String:', single_str) split = single_str.split(delimiter) print('List:', split)Output
String: Java,Python,Go List: ['Java', 'Python', 'Go']Using the aforesaid delimiter to divided the drawstring returns the original list, truthful join() and split() round-trip cleanly.
Splitting only n times
The split() method takes an optional 2nd statement that limits really galore splits are performed, which is useful erstwhile only the first fewer fields matter.
names = ['Java', 'Python', 'Go'] delimiter = ',' single_str = delimiter.join(names) split = single_str.split(delimiter, 1) print('List:', split)Output
List: ['Java', 'Python,Go']Because the divided count was group to 1, the cognition ran only erstwhile and near the remaining delimiter successful place.
Performance comparison: which subordinate method is fastest?
When combining strings aliases lists, the method you take has existent capacity implications, particularly arsenic the information grows. The cardinal thought is clip complexity: join() and extend() tally successful linear O(n) time, while many times utilizing + successful a loop runs successful quadratic O(n^2) clip because each + creates a brand-new entity and copies each the existing elements again.
Benchmark results for mini vs. ample lists
To make this concrete, the pursuing benchmark builds a drawstring of 100,000 items 2 ways, utilizing join() and utilizing += successful a loop, and times each pinch the timeit module.
import timeit words = [str(i) for one in range(100_000)] def with_join(): return ",".join(words) def with_plus_loop(): s = "" for w in words: s += w + "," return s print(f"join : {timeit.timeit(with_join, number=20) / 20 * 1000:.2f} ms") print(f"+= : {timeit.timeit(with_plus_loop, number=20) / 20 * 1000:.2f} ms")On 1 trial instrumentality moving Python 3.14, this produced the pursuing output (your nonstop numbers will alteration by hardware):
Output
join : 1.48 ms += : 12.61 msIn this run, join() was astir 8 times faster than building the drawstring pinch +=. The spread widens arsenic the database grows, which is the applicable consequence of the O(n) versus O(n^2) difference. The aforesaid shape holds for lists: concatenating 1,000 lists of 1,000 integers each pinch repeated retired = retired + lst took astir 540 sclerosis successful our testing, while list.extend() took astir 1 sclerosis and itertools.chain() astir 3 ms, since the repeated + rebuilds and copies the increasing database connected each step.
Time and abstraction complexity by method
The array beneath summarizes the complexity and representation behaviour of each method truthful you tin take based connected the size and style of your data.
| str.join() | O(n) | No (single pass) | Joining a database of strings into 1 string |
| + successful a loop | O(n²) | Yes (new entity each step) | Avoid for ample data; good for a azygous mini merge |
| list.extend() | O(n) | No (in place) | Growing an existing list |
| itertools.chain() | O(n) | No (lazy iterator) | Merging galore aliases very ample lists |
Choose the method that fits your usage case: join() for strings, extend() aliases chain() for lists, and reserve a azygous + for small, one-off merges.
Method comparison table
Beyond earthy performance, the methods disagree successful what they are for, really readable they are, and which Python versions support them. The array beneath compares the main options astatine a glance.
| str.join() | Join a database of strings into 1 string | str | High | All 3.x |
| + operator | Concatenate 2 lists aliases 2 strings | new database / str | High | All 3.x |
| list.extend() | Add items to an existing database successful place | modifies list | High | All 3.x |
| * unpacking | Merge respective lists into a caller list | new list | Medium | 3.5+ |
| itertools.chain() | Iterate complete galore lists without copying | iterator | Medium | All 3.x |
| dict | operator | Merge 2 dictionaries | new dict | High | 3.9+ |
Modern alternatives: unpacking and the | operator
Recent Python versions added cleaner syntax for merging collections. The * unpacking operator, shown earlier, is the idiomatic modern measurement to merge lists into a caller list. For dictionaries, PEP 584 introduced the | merge usability successful Python 3.9, giving dictionaries the aforesaid benignant of concise merge syntax that + gives lists.
defaults = {"theme": "light", "lang": "en"} overrides = {"lang": "fr"} settings = defaults | overrides print(settings)Output
{'theme': 'light', 'lang': 'fr'}When the aforesaid cardinal appears successful some dictionaries, the worth from the right-hand dictionary wins, which is why lang becomes "fr". There is besides an in-place version, |=, which updates the near dictionary alternatively of creating a caller one.
Some applicable usage cases
These methods representation people onto mundane tasks, truthful it helps to spot erstwhile each 1 shines.
-
The first communal lawsuit is utilizing join() for strings: erstwhile you person a database of strings and request a azygous delimited string, join() is the preferred method. This is useful for building a condemnation from a database of words aliases combining names pinch commas, arsenic shown passim this tutorial.
-
The 2nd communal lawsuit is combining lists pinch itertools.chain(): for merging aggregate lists, particularly ample ones, itertools.chain() offers a memory-efficient solution because it avoids creating intermediate lists. This matters erstwhile moving pinch ample datasets aliases erstwhile you request to process elements from respective lists successful a azygous iteration. You tin publication much successful the tutorial connected concatenating lists successful Python.
Combining lists pinch dictionaries aliases sets
Lists, dictionaries, and sets behave differently, truthful combining them requires a small care. Lists are ordered sequences, dictionaries are collections of key-value pairs (ordered by insertion since Python 3.7), and sets are unordered collections of unsocial elements. The examples beneath show really to merge a database pinch each of the different two.
To harvester a database pinch a dictionary, extract the dictionary’s keys aliases values and concatenate them pinch the list. This is useful erstwhile merging information from different sources.
my_list = [1, 2, 3] my_dict = {'a': 4, 'b': 5} combined_keys = my_list + list(my_dict.keys()) print(combined_keys) combined_values = my_list + list(my_dict.values()) print(combined_values)Output
[1, 2, 3, 'a', 'b'] [1, 2, 3, 4, 5]In the codification above, list() converts the dictionary’s keys aliases values into a list, which is past concatenated pinch my_list utilizing the + operator.
To harvester a database pinch a set, person the group to a database first, since sets are unordered and cannot beryllium concatenated to a database directly.
my_list = [1, 2, 3] my_set = {4, 5, 6} combined = my_list + list(my_set) print(combined)Output
[1, 2, 3, 4, 5, 6]Here list() turns the group into a database earlier concatenation. Note that the bid of elements coming from the group is not guaranteed, because sets are unordered.
FAQs
1. How to subordinate a database of strings successful Python?
To subordinate a database of strings into a azygous string, telephone the join() method connected a separator and walk the database arsenic the argument, utilizing the shape separator.join(list). The separator tin beryllium immoderate string, specified arsenic a comma aliases a space.
words = ['Hello', 'World'] sentence = ' '.join(words) print(sentence)This prints Hello World. If the database contains non-string items, person them first pinch map(str, list).
2. How tin I subordinate 2 lists successful Python?
To harvester 2 lists into 1 caller list, usage the + usability for a speedy merge, aliases itertools.chain() for amended capacity pinch ample lists. Use list.extend() if you want to turn an existing database successful spot alternatively than create a caller one.
list1 = [1, 2] list2 = [3, 4] combined = list1 + list2 print(combined)This prints [1, 2, 3, 4].
3. What does join() do successful Python?
The join() method concatenates the strings successful an iterable into a azygous string, separated by the drawstring you telephone it on. It useful connected immoderate iterable of strings (lists, tuples, generators) and ever returns a string, which is why it is simply a method of str alternatively than list.
4. What does strip() do successful Python?
The strip() method removes starring and trailing whitespace (or different specified characters) from a drawstring and returns the cleaned string. It is often utilized to tidy up individual items earlier aliases aft joining them, for illustration removing stray spaces parsed from a file.
5. What is the correct syntax for str.join() successful Python?
The correct syntax is separator.join(iterable), wherever the separator is the drawstring placed betwixt elements and iterable is the database (or different iterable) of strings to join. A predominant correction is penning list.join(separator), which does not beryllium and raises an AttributeError.
print("-".join(["2026", "06", "09"]))This prints 2026-06-09, showing the separator placed betwixt each element.
6. How do you subordinate a Python database of integers into a azygous string?
Convert each integer to a drawstring first, because join() accepts only strings. The simplest measurement is ",".join(map(str, numbers)), which applies str to each constituent earlier joining.
numbers = [1, 2, 3] print(",".join(map(str, numbers)))This prints 1,2,3. Joining the integers straight would raise TypeError: series point 0: expected str instance, int found.
7. How do you subordinate 2 abstracted lists into 1 database successful Python?
To nutrient a mixed database (not a string), usage the + operator, the * unpacking operator, list.extend(), aliases itertools.chain(). This is different from join(), which ever returns a drawstring alternatively than a list.
a = [1, 2] b = [3, 4] print([*a, *b])This prints [1, 2, 3, 4].
8. What is the quality betwixt join() and concatenation utilizing + successful Python?
The join() method is built for combining galore strings efficiently successful a azygous walk (O(n)), while + creates a caller entity each clip it runs. Using + erstwhile connected 2 mini values is fine, but utilizing + many times successful a loop is O(n^2) and slow, truthful join() is preferred for combining a database of strings.
9. How do you subordinate a database pinch a newline characteristic successful Python?
Use "\n" arsenic the separator, truthful each database constituent appears connected its ain line. This is the modular measurement to hole a database for penning to a matter file.
lines = ["first", "second", "third"] print("\n".join(lines))This prints each connection connected a abstracted line.
10. Can you subordinate a database that contains None values?
Not directly, because a None worth raises TypeError: series point N: expected str instance, NoneType found. Filter the None values retired pinch a generator expression, aliases person each constituent pinch str() if you want a placeholder.
items = ["a", None, "b"] print(",".join(x for x in items if x is not None))This prints a,b.
11. When should you usage itertools.chain() alternatively of the + operator?
Use itertools.chain() erstwhile merging galore lists aliases very ample ones, because it returns a lazy iterator and avoids building intermediate lists, keeping representation usage low. The + usability is good for a azygous merge of mini lists, but chaining galore + operations copies the increasing consequence many times and becomes slow.
12. Why does Python usage str.join(list) alternatively of list.join(str)?
Because join() useful pinch immoderate iterable and ever returns a string, it makes consciousness to specify it erstwhile connected the drawstring people alternatively than copy it crossed each iterable type. The separator is people the drawstring you telephone the method on, which is why the creation is separator.join(iterable).
Conclusion
In this tutorial, you learned the various ways to subordinate and harvester lists successful Python. You joined a database of strings pinch the join() method and customized the separator, handled lists of integers, mixed types, None values, and nested lists, and concatenated lists utilizing the + operator, list.extend(), the * unpacking operator, and itertools.chain(). You besides compared the methods by capacity and complexity, saw why join() is simply a drawstring method, and explored modern alternatives for illustration the dictionary | usability successful Python 3.9+.
To further heighten your knowledge of Python programming, we urge checking retired the pursuing tutorials:
- Python String Concatenation: Techniques, Examples, and Tips
- How to Concatenate Lists successful Python
- How to Add Elements to a List successful Python
- How To Use List Methods successful Python 3
- How to Remove Spaces from a String successful Python
This activity is licensed nether a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
English (US) ·
Indonesian (ID) ·