6

Many programming languages, including Python, support an operation like this:

", ".join(["1","2","3"])

which returns the string

"1, 2, 3"

I understand that this is the case, but I don't understand the design decision behind it - surely it would be more semantically valid to perform the join operation on the list, like so:

["1","2","3"].join(", ")

If anyone could explain the design decision and shed some light on it I'd appreciate it.

Edit: It looks like Javascript has the join method on the list; if anyone has examples for which convention particular languages follow, feel free to comment/answer about the choice in that particular language too.

jackweirdy
  • 5,632
  • 4
  • 24
  • 33
  • Note that your example *doesn't work* in python. The list must contain only strings. – mgilson Apr 30 '13 at 13:43
  • Lists are, in some sense, a lower level (more basic part of) of the language. so strings know about lists, but lists don't know about strings. – Hal Canary Apr 30 '13 at 13:44
  • I've edited the syntax to reflect that - the question was more about the overall semantics than that particular operation though :) – jackweirdy Apr 30 '13 at 13:44

1 Answers1

3

For python, there are a few arguments against it. First, if it is a string method that accepts an arbitrary iterable, then you only need to support the join method on string objects and it automagically works with anything iterable. Otherwise, custom iterable objects would also need to support a join method, etc. etc.

consider:

", ".join(["1","2","3"])
", ".join(("1","2","3"))
", ".join(str(x) for x in xrange(1,4))
", ".join({'1':None,'2':None,'3':None})
", ".join({'1','2','3'})  #set literal syntax -- python2.7+
", ".join("123")

6 different types all supported very simply by a single method (and I've only touched builtin types).

Second, you can only join a list if everything in it is a basestring type. It seems silly to provide a method on a list which would raise an exception if you used it on a list with the wrong contents -- At least, the API here seems somewhat tricky (to me). Of course, you could argue that list.remove can raise an exception if called with the wrong arguments. And that's true -- But that in general you're only removing a single item. It operates on a lower level than join should. Of course, this argument is weaker than the first one I proposed, so if you don't like it, just fall back on argument 1.

mgilson
  • 300,191
  • 65
  • 633
  • 696