Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending the same string to a list of strings in Python

Tags:

python

list

I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:

list1 = ['foo', 'fob', 'faz', 'funk'] string = 'bar'  *magic*  list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar'] 

I tried for loops, and an attempt at list comprehension, but it was garbage. As always, any help, much appreciated.

like image 324
Kevin Avatar asked Jan 12 '10 16:01

Kevin


People also ask

How do you add a string to a list of strings?

To append string to beginning of list we have used [a] + l1 and the string will get appended to the list at the beginning.

Can you concatenate a string to a list in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


2 Answers

The simplest way to do this is with a list comprehension:

[s + mystring for s in mylist] 

Notice that I avoided using builtin names like list because that shadows or hides the builtin names, which is very much not good.

Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):

(s + mystring for s in mylist) 

These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.

like image 138
gahooa Avatar answered Oct 06 '22 18:10

gahooa


my_list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' my_new_list = [x + string for x in my_list] print my_new_list 

This will print:

['foobar', 'fobbar', 'fazbar', 'funkbar'] 
like image 30
Tendayi Mawushe Avatar answered Oct 06 '22 19:10

Tendayi Mawushe