bphi
bphi

Reputation: 3195

Python Inline Generator

I'm attempting to interleave a value into a list.

interleave(1, ['A', 'B', 'C']) -> [1, 'A', 1, 'B', 1, 'C']

There are a number of ways to solve this problem, but I thought more_itertools.interleave would be the most readable. However to use this function I need to create a generator that yields 1 forever. Clearly this can be done with

def gen1():
    while True:
        yield 1

but this feels more complicated than necessary.

Is there an elegant way to replace ... in the snippet below to create an inline generator such that

res = more_itertools.interleave(..., ['A', 'B', 'C'])
assert list(res) == [1, 'A', 1, 'B', 1, 'C']

... = (1 for _ in ['A', 'B', 'C']) clearly works, but I wouldn't call it elegant.

Upvotes: 1

Views: 982

Answers (3)

fruitbat
fruitbat

Reputation: 88

def interleave(a,list1):
    newlist=[]
    for x in list1:newlist.extend([a,x])
    return newlist
print(interleave(1,['A','B','C']))

prints

[1, 'A', 1, 'B', 1, 'C']

Upvotes: 0

blhsing
blhsing

Reputation: 106543

You can also use a list comprehension like this:

def interleave(value, lst):
    return [j for i in lst for j in (value, i)]

So that interleave(1, ['A', 'B', 'C']) returns:

[1, 'A', 1, 'B', 1, 'C']

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60974

itertools.repeat. I don't know how interleave is implemented, but you can do the same thing with chain and zip:

from itertools import chain, repeat

print(list(chain.from_iterable(zip(repeat(1), ['A', 'B', 'C']))))
# [1, 'A', 1, 'B', 1, 'C']

Upvotes: 3

Related Questions