Inserting a string into a list without getting split into characters

Question:

I’m new to Python and can’t find a way to insert a string into a list without it getting split into individual characters:

>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']

What should I do to have:

['foo', 'hello', 'world']

Searched the docs and the Web, but it has not been my day.

Asked By: Dheeraj Vepakomma

||

Answers:

Don’t use list as a variable name. It’s a built in that you are masking.

To insert, use the insert function of lists.

l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']
Answered By: Spencer Rathbun

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')
Answered By: Rafe Kettler
>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']
Answered By: mac

Sticking to the method you are using to insert it, use

list[:0] = ['foo']

http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types

Answered By: Iacks

You have to add another list:

list[:0]=['foo']

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']
Answered By: juliomalegria

best put brackets around foo, and use +=

list+=['foo']
Answered By: Rik

I suggest to add the ‘+’ operator as follows:

list = list + [‘foo’]

Hope it helps!

ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']

or (use insert function where you can use index position in list)

ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']
Answered By: Abhishek Patil
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.