Inserting a string into a list without getting split into characters
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.
To add to the end of the list:
list.append('foo')
To insert at the beginning:
list.insert(0, 'foo')
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
Another option is using the overloaded + operator
:
>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']
best put brackets around foo, and use +=
list+=['foo']