3

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?

mazore
  • 984
  • 5
  • 11
  • 6
    What if you have a list of ints or arbitrary objects? – taras Nov 18 '20 at 08:24
  • 4
    Because `join` is defined on string, you can use it to join any sequence, not just a list: a tuple, a set, a generator. Even some iterable type that I write myself. Much more useful having it on str than list. – khelwood Nov 18 '20 at 08:25
  • Cast them to string like JavaScript... – adir abargil Nov 18 '20 at 08:25

3 Answers3

1

.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

Wasif
  • 14,755
  • 3
  • 14
  • 34
0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
TheCoolDrop
  • 796
  • 6
  • 18
0

Basically, join only works on lists of strings; it does not do any type coercion. joining a list that has one or more non-string elements will raise an exception. You can find the reason for that in the article: http://www.faqs.org/docs/diveintopython/odbchelper_join.html

Ananth
  • 787
  • 5
  • 18