Inserting a string into a list without getting split into characters

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')

Solution 2 - Python

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

Solution 3 - Python

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

Solution 4 - Python

best put brackets around foo, and use +=

list+=['foo']

Solution 5 - Python

>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']

Solution 6 - Python

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']

Solution 7 - Python

You have to add another list:

list[:0]=['foo']

Solution 8 - Python

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']

Solution 9 - Python

I suggest to add the '+' operator as follows:

list = list + ['foo']

Hope it helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDheeraj VepakommaView Question on Stackoverflow
Solution 1 - PythonRafe KettlerView Answer on Stackoverflow
Solution 2 - PythonIacksView Answer on Stackoverflow
Solution 3 - PythonjuliomalegriaView Answer on Stackoverflow
Solution 4 - PythonRikView Answer on Stackoverflow
Solution 5 - PythonmacView Answer on Stackoverflow
Solution 6 - PythonSpencer RathbunView Answer on Stackoverflow
Solution 7 - PythonSome programmer dudeView Answer on Stackoverflow
Solution 8 - PythonAbhishek PatilView Answer on Stackoverflow
Solution 9 - PythonAntonio Moreno MartínView Answer on Stackoverflow