How do I add text to every other item in a python list?

  • A+
Category:Languages

I have a list like:

mylist = ["1", "2", "3", "4", "5"] 

I want to add some text to every other item so it looks like this:

mylist = ["1a", "2", "3a", "4", "5a"] 

I wrote this, which works fine for every item. How do I make it apply only to every other item?

mylist2 = ["a" + item for item in mylist] 

 


One way to do it would be this:

mylist = ["1", "2", "3", "4", "5"] res = [x + ('a' if i%2 == 0 else '') for i, x in enumerate(mylist)] 

which results in:

['1a', '2', '3a', '4', '5a'] 

This approach takes advantage of the fact that the index of the terms you want to change when divided by 2 have a remainder of 1. See modulo

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: