1

in a python program I have a list that I would like to modify:

a = [1,2,3,4,5,1,2,3,1,4,5]

Say every time I see 1 in the list, I would like to replace it with 10, 9, 8. My goal is to get:

a = [10,9,8,2,3,4,5,10,9,8,2,3,10,9,8,4,5]

What's a good way to program this? Currently I have to do a 'replace' and two 'inserts' every time I see a 1 in the list.

Thank you!

JimmyK
  • 940
  • 8
  • 13

4 Answers4

0

If you want to do everything in place, then you could try do something like this:

while i < len(a):
    if a[i] == 1:
        a[i : i + 1] = [10, 9, 8]
    i += 1

But IMHO it would be better to build a new list from scratch rather than modifying the existing one in place.

Gevorg Davoian
  • 454
  • 5
  • 12
0

This probably isn't very efficient but it's fun to one-line things:

[item for sublist in [[x] if x != 1 else [10, 9, 8] for x in a] for item in sublist]
Sean
  • 2,864
  • 1
  • 23
  • 31
0

Create a new list, with values replaced:

b = []
for z in a:
    b.extend([10, 9, 8] if z == 1 else [z])
Daniel
  • 40,885
  • 4
  • 53
  • 79
0

Just a normal list comprehension would do the job

>>> [y for x in a for y in ([10,9,8] if x==1 else [x])]
[10, 9, 8, 2, 3, 4, 5, 10, 9, 8, 2, 3, 10, 9, 8, 4, 5]
Sunitha
  • 11,422
  • 2
  • 17
  • 22