I’m new to python and completely confused,
why ','.join('a','b','c')
rised an error, a ",".join(['a','b','c'])
didn’t.
Why the code below have the same output?
In [3]: ",".join({'a':1,'b':2,'c':3})
Out[3]: 'b,a,c'
In [4]: ",".join({'a':2,'b':1,'c':3})
Out[4]: 'b,a,c'
In [5]: ",".join({'a':3,'b':2,'c':1})
Out[5]: 'b,a,c'
The docs on str.join
state that the method takes an iterable
which is any type that can be iterated over (list, tuple, etc.):
str.join(iterable)¶
Return a string which is the concatenation of the strings in iterable. A
TypeError
will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
In your first example, you pass three arguments to a method which expects one so receive a TypeError
, whereas you use the method as intended in the example where you pass a list (indicated so through the use of square brackets). In your typed examples, you are passing dictionaries which are also iterable, however, when iterated over, they yield their keys (note: the order is undetermined). So the keys of say: {'a':1,'b':2,'c':3}
are: 'a'
, 'b'
and 'c'
and since these are all strings, the method works fine to join them together with a comma
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With