Why is it string.join(list) instead of list.join(string)?

Evan Fosmark picture Evan Fosmark · Jan 29, 2009 · Viewed 1.3M times · Source

This has always confused me. It seems like this would be nicer:

my_list = ["Hello", "world"]
# Produce: "Hello-world"

Than this:

my_list = ["Hello", "world"]
# Produce: "Hello-world"

Is there a specific reason it is like this?


recursive picture recursive · Jan 29, 2009

It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.

For example:

'_'.join(['welcome', 'to', 'stack', 'overflow'])
'_'.join(('welcome', 'to', 'stack', 'overflow'))

Using something other than strings will raise the following error:

TypeError: sequence item 0: expected str instance, int found