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]
We can use format() function which allows multiple substitutions and value formatting. Another approach is to use map() function. The function maps the beginning of all items in the list to the string.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With