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

Viewed 7083

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]
5 Answers

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

Try This:

for i in range(0, len(mylist), 2):
    mylist[i] = mylist[i] + "a"

EDIT 1:

for i in range(0, len(mylist), 2):
    mylist[i] += "a"

use enumerate and a modulo to test odd or even values with a ternary.

mylist = ["1", "2", "3", "4", "5"]
mylist2 = [item if i%2 else "a" + item for i,item in enumerate(mylist)]

result:

>>> mylist2
['a1', '2', 'a3', '4', 'a5']

to get 1a, etc... just switch "a" + item by item + "a"

A bit weird solution, which makes use of iterators:

>>> from itertools import cycle
>>> mylist = ["1", "2", "3", "4", "5"]
>>> suffix = cycle(["a", ""])
>>> [l + s for l, s in zip(mylist, suffix)]
['1a', '2', '3a', '4', '5a']

EDIT

As suggested by Netwave in comments, here is the very-super-pythonic solution!

>>> import itertools, operator
>>> list(map(operator.add, mylist, itertools.cycle(("a", ""))))
['1a', '2', '3a', '4', '5a']

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

Related