Generator expression resembling append behavior

This is more of a programming exercise than a real world problem. I am looking for a generator expression similar to append behavior.

Consider:

 def combine(sequence, obj): for item in sequence: yield item yield obj s = ''.join(combine(sequence, obj)) 

This generator is mostly reminiscent of append . In the workflow of my program, the above is as fast as

 sequence.append(obj) s = ''.join(sequence) 

Now I'm wondering if there is a neat genexpr generator genexpr with

 s = ''.join(genexpr) 

which is similar to append behavior above without performance limitations.

 s = ''.join(_ for a in [sequence, [obj]] for _ in a) 

not working well.

+4
source share
2 answers

Try using chain from the itertools module:

 ''.join(chain(sequence, [obj])) 

If you do not want to create a new list for obj , you can try the following:

 ''.join(chain(sequence, repeat(obj,1))) 

I would use [obj] as it is more readable, and I doubt that the repeat iterator has less overhead than list .

+4
source

I'm not sure about your specific example, but I found that just using + [b] was about as fast as everything else, even with large lists. Here is my test code:

 import timeit from itertools import chain, repeat a=map(str,range(100000)) b='b' def combine(sequence,obj): for item in sequence: yield item yield obj def test1(): return ','.join(a+[b]) def test2(): return ','.join(combine(a,b)) def test3(): return ','.join(chain(a,repeat(b,1))) def test4(): return ','.join(chain(a,[b])) def test5(): return ','.join(y for x in [a,[b]] for y in x) count=100 print 'test1: %g'%timeit.timeit(test1,number=count) print 'test2: %g'%timeit.timeit(test2,number=count) print 'test3: %g'%timeit.timeit(test3,number=count) print 'test4: %g'%timeit.timeit(test4,number=count) print 'test5: %g'%timeit.timeit(test5,number=count) 

And here are the results on my system:

 test1: 0.475413 test2: 0.977652 test3: 0.550071 test4: 0.548962 test5: 0.968162 
+2
source

Source: https://habr.com/ru/post/1441104/


All Articles