Why is .join() a property of string not list?

Viewed 199

When joining a list in python, join is a function of a str, so you would do

>>>', '.join(['abc', '123', 'zyx'])
'abc, 123, zyx'

I feel like it would be more intuitive to have it as a property of a list (or any iterator really),

>>>['abc', '123', 'zyx'].join(', ')
'abc, 123, zyx'

Why is this?

3 Answers

.join() is a property of str object, not list. Unfortunately like javascript it isn't posssible to add custom methods to built-in objects, but you can create new classes like:

class MyString:
    def __init__(self, string):
        self.string = string
    def join(self,sep):
        return sep.join(self.string)

mystring = MyString("this is the string")
print(mystring.join())

To get original string use mystring.string and you can apply normal python properties and methods

The true why can probably only be given to you by developers and thinkers behind Python, but I will try to give it a jab.

Firstly if you had join on lists, when what would this operation mean for lists of arbitrary objects? For example if you had a list of HttpClient objects, what would the result of the join be? The answer is that it is probably not even valid to ask such question in the first place, since we can assign no meaning to joining arbitrary objects.

Secondly even if the operation is part of String objects API it does not make it impossible for it to also be an operation on objects of some arbitrary other class. This means that if you have a use case where you require .join() operation on lists, then you can create a special lists class which implements this behavior. You can achieve this using either inheritance or composition, whichever you prefer.

Related