Skip to content Skip to sidebar Skip to footer

Is There A "join" Like Function For Generic Lists In Python?

In Python, a list of strings can be joined together by ','.join(['ab', 'c', 'def']) But how could I easily join a list of numbers or some other things? Like this: 0.join([1, 2, 3]

Solution 1:

You could make one:

defjoin_generator(joiner, iterable):
    i = iter(iterable)
    yieldnext(i)  # First value, or StopIterationwhileTrue:
       # Once next() raises StopIteration, that will stop this# generator too.
       next_value = next(i)
       yield joiner
       yield next_value

joined = list(join_generator(0, [1, 2, 3, 4]))

Solution 2:

Just because everybody loves unreadable one-liners:

import itertools

defjoin(sep, col):
    return itertools.islice(itertools.chain.from_iterable(itertools.izip(itertools.repeat(sep), col)), 1, None)

P.S.: better use RemcoGerlich's answer. It's way more readable.

Solution 3:

Not the way you are wanting to do it. You could write a for loop for the sum or you could write a for loop and have each item added as you go through your list. Otherwise, you won't be able to make the adjustment you're looking for.

Solution 4:

As everyone is telling you, join is a string method instead of a list method.

But you can always do:

[int(x) for x in'0'.join(map(str, [1, 2, 3]))]

Solution 5:

For newer python versions the following should do

defjoin(joiner, iterable):
    """Small helper that does similar things as "foo".join("bar") """
    it = iter(iterable)
    head, tail = next(it, None), it
    if head isnotNone:
        yield head

    for item in tail:
        yield joiner
        yield item


assertlist(join("a", range(4))) == [0, "a", 1, "a", 2, "a", 3]
assertlist(join("a", [])) == []
assertlist(join("a", [0])) == [0]

Did I miss some corner case?

Post a Comment for "Is There A "join" Like Function For Generic Lists In Python?"