r.hart
r.hart

Reputation: 59

Multiplying numbers in a list in python

I need a loop to multiply part of a list. I have multiply every Nth element (except 0th) by M. The list is called numbers, the multiplier is M, and the loop should start multiplying at the Nth number. This is what I have:

for i in range(0, len(numbers)):
  numbers[i]= int(numbers[i])

for M in range (N, len(numbers)):
  if numbers[N] > 0:
    numbers.append[N]
  if numbers[N] < 0:
    total = numbers
    print (total)

It keeps returning the wrong output, I've tried everything I can think of to fix it but it still won't work.

Upvotes: 1

Views: 1879

Answers (4)

tobias_k
tobias_k

Reputation: 82899

There a quite a few problems and oddities in your code:

  • you use M as the loop variable, thus overwriting the multiplier stored in M; better use i as in your first loop
  • your are appending to the list, instead of overwriting the numbers with numbers[i] = numbers[i] * M or just numbers[i] *= M
  • I don't see how the > 0 and < 0 checks relate to your question, but you should probably check numbers[i] instead of numbers[N], the letter being always the same
  • also, I don't see why you assign the entire numbers list (instead of e.g. just numbers[i] to total and print it...

You could also use a list comprehension and assign back to a slice of the original list:

>>> N, M = 3, 10
>>> numbers = list(range(10))
>>> numbers[N::N] = [x*M for x in numbers[N::N]]
>>> numbers
[0, 1, 2, 30, 4, 5, 60, 7, 8, 90]

Upvotes: 1

user2314737
user2314737

Reputation: 29307

With map:

map(lambda (i, el): el*M if i%N==0 else el, enumerate(numbers))

Skipping the first index:

map(lambda (i, el): el*M if i%N==0 and i>0 else el, enumerate(numbers))

Upvotes: 0

niedzwiedzwo
niedzwiedzwo

Reputation: 126

numbers = [int(n) for n in numbers]

this is for the first function. It's called a list comprehension The second one you got M and N mixed up i guess. What is N anyways?

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You usually multiply a number with the asterisk (*). So we can multiply the i-th number with:

numbers[i] *= M

To multiply every N-th element except the first one, we can construct a range:

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

The last argument of the range is the step, it means that we thus each time increment i, until reach len(numbers)

Upvotes: 2

Related Questions