3 ms·
Except that it only makes sense in the context of strings, so it makes perfect sense to make it a string method.
by axiak 16y ago
Except that it only makes sense in the context of strings, so it makes perfect sense to make it a string method.
- deleted 16y ago[deleted]
- djacobs 16y agoIt seems to me like join makes sense in any context where you have multiple elements that you want joined. With strings, you happen to have a separator. But you might also want to join several lists into one flattened list. (Edit: I know there are ways to do this. The point is that join could be unified around this concept.) Even if you disagree, the line between methods and functions in Python really isn't standardized.
- koenigdavidmj 16y agoYou can join several lists into a flattened list as well: reduce(operator.add, list_of_lists) You can not say sum(), sadly, because it forces a restriction that you only sum numbers.
- dgouldin 16y agoIt's not pretty, but you can do it: >>> sum([['a', 'b', 'c'], ['d', 'e', 'f']], []) ['a', 'b', 'c', 'd', 'e', 'f'] This makes use of the optional start argument and list add operator. However, Python's docs suggest using itertools.chain instead: http://docs.python.org/library/functions.html#sum http://docs.python.org/library/functions.html#sum >>> import itertools >>> [l for l in itertools.chain(*[['a', 'b', 'c'], ['d', 'e', 'f']])] ['a', 'b', 'c', 'd', 'e', 'f'] (Of course you lose the benefit of a generator by using a list comprehension, but this is just an example.)
- jacobolus 16y agoYour second example is easier to just write as: >>> from itertools import chain >>> list_of_lists = [['a', 'b', 'c'], ['d', 'e', 'f']] >>> list(chain(*list_of_lists)) ['a', 'b', 'c', 'd', 'e', 'f'] That is, list(«foo») is clearer and more idiomatic than [x for x in «foo»].
- scottbessler 16y agoI may be missing something, but why isn't skipping your list comprehension maintaining the benefit of using a generator? >>> from itertools import chain >>> chain(*[['a', 'b', 'c'], ['d', 'e', 'f']])
- dgouldin 16y agoIt is, but I don't get to show you the result of the chain that way. :)