PiccolMan
PiccolMan

Reputation: 5366

How to add a word at the end of each element of a list?

I have the list:

mylist = ["all dogs go", "why does one", "fell down so hard I"]

Is there a function that will allow me to add the word "moo" to the end of each element in mylist?

Upvotes: 1

Views: 3490

Answers (3)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

Use list comprehensions:

>>> mylist[:] = [word.strip() + " moo" for word in mylist]
>>> print mylist
['all dogs go moo', 'why does one moo', 'fell down so hard I moo']

Upvotes: 7

Anshul Goyal
Anshul Goyal

Reputation: 76887

You can use a list comprehension to do that:

>>> mylist = ["all dogs go", "why does one", "fell down so hard I"]
>>> mylist = [x + " moo" for x in mylist]
>>> mylist
['all dogs go moo', 'why does one moo', 'fell down so hard I moo']

That creates a new list, so you can also use a for loop to do the same (which changes existing list object, though that shouldn't really matter in small examples like this one):

>>> mylist
['all dogs go', 'why does one', 'fell down so hard I']
>>> for idx in xrange(len(mylist)):
...     mylist[idx] = mylist[idx] + " moo"
... 
>>> mylist
['all dogs go moo', 'why does one moo', 'fell down so hard I moo']

As for your edited question, you could use the below if your pattern is valid for all elements:

>>> mylist = ["8 - 9 -", "7 - 6 -", "5 - 4 -"]
>>> mylist = [x[:-1] for x in mylist]
>>> mylist
['8 - 9 ', '7 - 6 ', '5 - 4 ']

Upvotes: 4

Alexander
Alexander

Reputation: 109546

just use append:

mylist.append('moo')
>>> mylist
['all dogs go', 'why does one', 'fell down so hard I', 'moo']

EDIT:

If you want to append 'moo' to EACH element in your list, use the suggestion by @mu (no pun intended). Sorry @ozgur, I didn't intentionally leave you out, the pun was intended...

Upvotes: 1

Related Questions