2

i got a listx =[1,2,3,4,5,6,7,8,9]

i want to alter every Nth item of the list. For example i want to modify for every 2 item step, let say i want to modify by +1 . so i want to get result = [1+1,2,3+1,4,5+1,6,7+1,8,9+1] =[2,2,4,4,6,6,8,8,9]

i can do this by using for-loop , by adding counter variable , then check the counter by counter%2==0. But this time i 'm just curious using single line statement. Here what i want =

newlistx=[i+1 for i in listx] <- this will modify all items, so i'm expecting i can use some internal indexing use in this iteration process, become like this :

newlistx=[i+1 if (__indexing__%step==0) else i for i in listx] where step=2.

Actually, i can use list.index() function , like this :

newlistx=[i+1 if listx.index(i)%2==0 else i for i in listx]

the problem this me thod only works if all the item is unique, if i got items which have same value then index() will return wrong value.

Again, i'm just curious if i can grab some internal indexing or counter , if exist.

2 Answers 2

7

You can use the enumerate function.

newlist = [x + 1 if n % step == 0 else x
           for (n, x) in enumerate(oldlist)]

The enumerate function iterates over a sequence and yields the objects with their indexes.

Sign up to request clarification or add additional context in comments.

2 Comments

Your use of n for the index and i for the list item makes me cringe.
@Markus: Indeed, I never would have written code like that on my own. Fixed.
1
new_list = [n + 1 if i & 1 else n for i, n in enumerate(listx)]

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.