0

I created a list like this:

n = [0,0,0,0,0]

now I want to add [100] at index [1,2,3]. so list will become like this -

n = [0,100,100,100,0]

another example: adding[200] at index [3,4], list will become-

n = [0,100,100,300,200]

We can do this by using loops, but using loops it will take O(n) time. I want to know can we add a value at multiple index of a list without using loops?

1
  • Unless you use a specialised data structure (and I'm not sure I know of one with suitable characteristics), modifying k different elements in a list will be O(k) at best, no matter the method you use. Commented Mar 27, 2021 at 10:03

2 Answers 2

3

You can use can numpy (known for his performant code) arrays, the synta is easy

import numpy as np

n = np.zeros(5) # make array of float, use 'np.zeros(5).astype(int)' for int
n[1:4] = 100
n[3:5] += 200

If you print the between each step

[  0   0   0   0   0]
[  0 100 100 100   0]
[  0 100 100 300 200]
Sign up to request clarification or add additional context in comments.

Comments

1

Given a list and a list of pairs of indexes and values you want to add on those indexes, you can achieve this the following way

lst = [0] * 10
values = [(3, 100), (5, 200), (7, 300)]

for index, value in values:
     lst[index] = value

print(lst)  # [0, 0, 0, 100, 0, 200, 0, 300, 0, 0]

In general, you have to iterate over the indexes you want to use, so it cannot be better than this - O(m), where m is the number of indexes.

1 Comment

When answering a problem, it's recommended to use the OP's values, not other values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.