This is more a programming exercise than a real-world problem: I am looking for a generator expression that resembles the behavior of append.
Consider:
def combine(sequence, obj):
for item in sequence:
yield item
yield obj
s = ''.join(combine(sequence, obj))
This generator basically resembles append. In the workflow of my program the above is as fast as
sequence.append(obj)
s = ''.join(sequence)
I am now wondering if there is a neat generator expression genexpr with
s = ''.join(genexpr)
that resembles the append behavior above without performance caveats.
s = ''.join(_ for a in [sequence, [obj]] for _ in a)
performs bad.
Try using
chainfromitertoolsmodule:If you don’t want to create a new
listforobj, then you may try this:I would use
[obj]as it’s more readable and I doubt thatrepeatiterator has a less overhead thanlistcreation.