Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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]
like image 725
Alligator Avatar asked Oct 30 '18 15:10

Alligator


People also ask

How do you add a string to every element in a list Python?

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.


Video Answer


3 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

like image 77
Ma0 Avatar answered Oct 15 '22 15:10

Ma0


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"
like image 34
Rohit-Pandey Avatar answered Oct 15 '22 14:10

Rohit-Pandey


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"

like image 35
Jean-François Fabre Avatar answered Oct 15 '22 15:10

Jean-François Fabre