Multiply every Nth index in list

homework
python

#1

I am trying to multiply every third index in the below list and output the list with every third index multiplied by 5.

numbers = [1,2,3,4,5,6]

N = 3
M = 5

for i in range(0, len(numbers), N):
numbers[N-1] = N * M
print(numbers)

output:
[1, 2, 15, 4, 5, 6]

it’s not multiplying the 6. Any help would be great!


#2

The range() function has a step value which will come in handy here. Just start with the third index, and step in three’s.

>>> numbers = [1,2,3,4,5,6]
>>> for i in range(2, len(numbers), 3):
    numbers[i] *= 5

    
>>> numbers
[1, 2, 15, 4, 5, 30]
>>> 

#3

@mtf, step is being used?

@pycoder64045, you take steps of 3, so we to index 3 and then to index 6, but index 6 doesn’t exist. Index 5 is the highest, which is why 6 isn’t multiplied


#4

Must need to zoom. Print is getting smaller and harder to read every day. The code didn’t look right, regardless, which prompted an example.


#5

Ok thank you but if I change the multiplier to 2 and the step to 7:

for i in range(2, len(numbers), 7):
numbers[i] *= 2
print(numbers)

I get this output
[1, 2, 6, 4, 5, 6]

Which should be: [1,2,3,4,5,6]:


#6

why do you have a start value of 2 now?


#7

Which is correct, and expected. The third index is the only one in the range, so is the only one to be doubled.


#8

Here is the problem:

We are passing in 3 inputs.
•a list of numbers
•a multiplier value, M
•a value, N

You should multiply every Nth element (do not multiply the 0th element) by M. So, if N is 3, you start with the 3rd element, which is index 2.
If there are less than N elements then you should output the unchanged input list.

Code:
numbers = [1,2,3,4,5,6,]

N = 7
M = 2

N & M can change and do

for i in range(2, len(numbers), N):
numbers[i] *= M
print(numbers)


#9

but then here:

for i in range(2, len(numbers), N):

the start value should be N-1, given N might change.


#10

Thank you. That was it.


#11

We get straight to the point when a link to the lesson is provided in the opening post. Help others by not making it so hard for them to know what lesson you are on. Guessing is no comfort.


#12

Is this even an exercise? I don’t remember this one


#13

I’m only guessing. Will have to seek it out, assuming this is the correct unit.

Update: Cannot seem to find a lesson that looks like this one. We will need the OP to bring us up to speed, lesson or homework?


#14

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.