Similar to this question, but instead of replacing one item with another, I'd like to replace any occurrences of one item with the contents of a list.
orig = [ 'a', 'b', 'c', 'd', 'c' ]
repl = [ 'x', 'y', 'z' ]
desired = [ 'a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z' ]
# these are all incorrect, or fail to compile
[ repl if x == 'c' else x for x in orig ]
[ [a for a in orig] if x == 'c' else x for x in orig ]
[ (a for a in orig) if x == 'c' else x for x in orig ]
[ a for a in orig if x == 'c' else x for x in orig ]
Edit: made it clear I meant to replace all occurrences of the item, rather than just the first. (Apologies to anyone who didn't cover that case in their answer.)
And of course, if you don't know that
'c'
is at index 2, you can useorig.index('c')
to find out that information.If you enumerate backwards, you can extend the list as you go because the items you move have already gone through the enumeration.
Yet another way:
Different approach: when I'm doing replacements, I prefer to think in terms of dictionaries. So I'd do something like
where the last line is the standard flattening idiom.
One advantage (disadvantage?) of this approach is that it'll handle multiple occurrences of
'c'
.[update:]
Or, if you prefer:
On the revised test case:
No need for anything fancy:
To find
2
you can search fororig.index('c')
.if repl is not a list, just use
list(repl)