Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate generator and item

I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence:

i for i in tuple(my_generator) + (my_value,)

The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my_generator" once.

Better approch would be:

def con(seq, item):
    for i in seq:
        yield seq
    yield item

i for i in con(my_generator, my_value)

But I was wondering whether it is possible to do it without that function definition

like image 675
TarGz Avatar asked Mar 14 '10 18:03

TarGz


3 Answers

itertools.chain treats several sequences as a single sequence.

So you could use it as:

import itertools

def my_generator():
    yield 1
    yield 2

for i in itertools.chain(my_generator(), [5]):
    print i

which would output:

1
2
5
like image 102
Mark Rushakoff Avatar answered Nov 14 '22 04:11

Mark Rushakoff


itertools.chain()

like image 21
Ignacio Vazquez-Abrams Avatar answered Nov 14 '22 06:11

Ignacio Vazquez-Abrams


Try itertools.chain(*iterables). Docs here: http://docs.python.org/library/itertools.html#itertools.chain

like image 5
Arkady Avatar answered Nov 14 '22 04:11

Arkady