T
T
Timebird2016-03-10 18:40:14
Python
Timebird, 2016-03-10 18:40:14

How to multiply every NINTH element of a list by 2?

Hello! A question. How to multiply every ninth element of a list by 2?
Tried like this, it doesn't work. I don't understand, what is the correct syntax?
The array samples_null_listcontains floating point numbers.

step_null_list = []
for i in range(samples_null_list[0], samples_null_list[-1], samples_null_list[8]):
    samples_list[i] *= 2
    step_null_list.append(samples_list[i])

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Andrey Myvrenik, 2016-03-10
@Timebird

Your code probably solves some problem, but not exactly described by you.
See range(start, stop[, step]) :

  • start -- first interval value
  • stop -- the last value of the interval
  • step -- step
for i in range(..) means for each i in the range from start to stop with step . You pass the values ​​of the samples_null_list array as start, stop and step , so the behavior of the loop depends on the values ​​of this array (namely the first, last and ninth element).

R
Radist_101, 2016-03-11
@Radist_101

new_list = []
for i, x in enumerate(my_list):
    if (i+1) % 9 == 0:
        x *= 2
    new_list.append(x)

V
Vladimir Martyanov, 2016-03-10
@vilgeforce

Use index access. And it will be for i in tange(list_length)...

A
abcd0x00, 2016-03-11
@abcd0x00

>>> lst = [1, 2, 3, 4, 5] * 10
>>> 
>>> out = [n * 2 if i % 9 == 0 else n
...        for i, n in enumerate(lst, 1)]
>>> out
[1, 2, 3, 4, 5, 1, 2, 3, 8, 5, 1, 2, 3, 4, 5, 1, 2, 6, 4, 5, 1, 2, 3, 4, 5, 1, 4, 3, 4, 5, 1, 2, 3, 4, 5, 2, 2, 3, 4, 5, 1, 2, 3, 4, 10, 1, 2, 3, 4, 5]
>>>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question