I was implementing something similar to Python's join function, where
join([a1, a2, ..., aN], separator :: String)
returns
str(a1) + separator + str(a2) + separator + ... + str(aN)
e.g.,
join([1, 2, 3], '+') == '1+2+3'
I was implementing something similar and was wondering, what is a good pattern to do this? Because there is the issue of only adding the separator if it is not the last element
def join(l, sep):
out_str = ''
for i, el in enumerate(l):
out_str += '{}{}'.format(el, sep)
return out_str[:-len(sep)]
I'm quite happy with this, but is there a canoncial approach?
join
the separator is the first argument to avoid ambiguity. \$\endgroup\$malloc/realloc()
call in each loop, but cPython special-cases this, so it's only N*O(1) = O(N). In native Python. string.join or sep.join are faster because they're one Python call, not N. See Is the time-complexity of iterative string append actually O(n^2), or O(n)? \$\endgroup\$delimiter
more thanseparator
\$\endgroup\$