0

I want to make a slice of array and then assign each element of a slice to a number and then update according to indices I provide.

For example:

[0, 0, 0, 0, 0] --> initial array

I want to assign 100 to first two elements i.e

a[0:2] = 100 for j in range(0,2)

so now the array becomes

[100, 100, 0, 0, 0]

now if i want to add 100 to the first three elements so the array should now become

[200, 200, 100, 0, 0]

what's the correct way to do this? I am getting a syntax error for the following code:

def arrayManipulation(n, queries):
n = 10
//queries is list of [[starting index, ending index, value to be updated]]
initialArray = [0]*n;
for i in queries:
    firstIndex = i[0]-1
    secondIndex = i[1]
    initialArray[firstIndex:secondIndex] = ((initialArray[j] += i[2]) for j in range(firstIndex, secondIndex))
    print(initialArray)

2 Answers 2

1

Use enumerate here It will let you access the indexs you are interested in and assign values or manipulate them

l = [0, 0, 0, 0, 0]

for idx, item in enumerate(l[:2]):
    l[idx] = 100

for idx, item in enumerate(l[:3]):
    l[idx] += 100

print(l)

*Note : Initial assignment can be done via (@ShadowRanger)

l[:2] = [100] * 2
Sign up to request clarification or add additional context in comments.

2 Comments

Note that for simple assignment (rather than mutation), you can do slice assignment more simply/efficiently, e.g. for setting the initial 100s, l[:2] = [100]*2. Bulk mutation (e.g. l[:3] += 100) would only work with third party types like numpy arrays.
@ShadowRanger Yep that is correct I do know that, I'm still fresh to programming, I have brief use of some techniques as such that slip my mind when responding but yes, I agree and should have known
0

The common way is to use range and a loop.

a = [0, 0, 0, 0]

for i in range(2):
    a[i] = 100

for i in range(3):
    a[i] += 100

print(a) # [200, 200, 100, 0]

Although, it is good to know that Python supports slice assignation.

a = [0, 0, 0, 0]

a[0:2] = [100, 100]

# To some extent, this even can be done
a[0:3] = map(lambda x: x + 100, a[0:3])

print(a) # [200, 200, 100, 0]

Comments

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.