Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit the value of every Nth item in a list

What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I would like to add 1 to every second item, which would give:

list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]

I've tried:

list1[::2]+1

and also:

for x in list1:
    x=2        
    list2 = list1[::x] + 1
like image 940
Nakusights Avatar asked Mar 15 '16 12:03

Nakusights


2 Answers

You could use slicing with a list comprehension as follows:

In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [27]: list1[1::2] = [x+1 for x in list1[1::2]]

In [28]: list1
Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11]
like image 88
gtlambert Avatar answered Sep 18 '22 15:09

gtlambert


numpy allows you to use += operation with slices too:

In [15]: import numpy as np

In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

In [17]: l[1::2] += 1

In [18]: l
Out[18]: array([ 1,  3,  3,  5,  5,  7,  7,  9,  9, 11])
like image 35
awesoon Avatar answered Sep 21 '22 15:09

awesoon