Home > Software engineering >  Inserting a list of values in place of a value in a list
Inserting a list of values in place of a value in a list

Time:04-27

I have a list of values:

a = [0.5, 2.3, 3.1, 1.4, 3.2, 2.2, 1.3, 1.5]

I would like to replace one of these values with a list of values.

b = [1.1, 1.6, 1.8]

For example, let us suppose that I want to replace the value 1.3 with the values in list b. I tried this method but did not get the desired result:

new_a = [b if x==1.3 else x for x in a]

In this way I insert a list into the list.

[0.5, 2.3, 3.1, 1.4, 3.2, 2.2, [1.1, 1.6, 1.8], 1.5]

The result I would like to achieve instead is:

[0.5, 2.3, 3.1, 1.4, 3.2, 2.2, 1.1, 1.6, 1.8, 1.5]

CodePudding user response:

The below method gives what you want. I have done this by getting the position of 1.3 in a (idx), then take the list up to that position, plus b plus the list after that position:

idx = a.index(1.3)
new_a = a[:idx]   b   a[idx 1:]

Output:

[0.5, 2.3, 3.1, 1.4, 3.2, 2.2, 1.1, 1.6, 1.8, 1.5]

CodePudding user response:

You can use the index method to get the index of the element with value 1.3. Then assign b to a slice of a (see the documentation regarding the semantics of assignment when the target is a slicing)

ix = a.index(1.3)
a[ix : ix   1] = b

print(a)

Output

[0.5, 2.3, 3.1, 1.4, 3.2, 2.2, 1.1, 1.6, 1.8, 1.5]
  • Related