6

What is the simplest method for replacing one item in a list with two?

So:

list=['t' , 'r', 'g', 'h', 'k']

if I wanted to replace 'r' with 'a' and 'b':

list = ['t' , 'a' , 'b', 'g', 'h', 'k']
Jasmine078
  • 389
  • 2
  • 4
  • 16

3 Answers3

11

It can be done fairly easily with slice assignment:

>>> l = ['t' , 'r', 'g', 'h', 'k']
>>> 
>>> pos = l.index('r')
>>> l[pos:pos+1] = ('a', 'b')
>>> 
>>> l
['t', 'a', 'b', 'g', 'h', 'k']

Also, don't call your variable list, since that name is already used by a built-in function.

arshajii
  • 127,459
  • 24
  • 238
  • 287
3

In case list contains more than 1 occurrences of 'r' then you can use a list comprehension or itertools.chain.from_iterable with a generator expression.But, if list contains just one such item then for @arshajii's solution.

>>> lis = ['t' , 'r', 'g', 'h', 'k']
>>> [y for x in lis for y in ([x] if x != 'r' else ['a', 'b'])]
['t', 'a', 'b', 'g', 'h', 'k']

or:

>>> from itertools import chain
>>> list(chain.from_iterable([x] if x != 'r' else ['a', 'b'] for x in lis))
['t', 'a', 'b', 'g', 'h', 'k']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • I gather the point here is to splice over *all* occurrences of `'r'`, but if (as in OP's example) there is only one occurrence this is pretty complicated for a simple splice. – kojiro Mar 10 '14 at 19:33
  • @kojiro May be I didn't read the question properly, for just one occurrence of course this is an overkill. – Ashwini Chaudhary Mar 10 '14 at 19:39
1

Here's an overcomplicated way to do it that splices over every occurrence of 'r'. Just for fun.

>>> l = ['t', 'r', 'g', 'h', 'r', 'k', 'r']
>>> reduce(lambda p,v: p + list('ab' if v=='r' else v), l, [])
['t', 'a', 'b', 'g', 'h', 'a', 'b', 'k', 'a', 'b']

Now go upvote one of the more readable answers. :)

kojiro
  • 74,557
  • 19
  • 143
  • 201