128

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.

Dheeraj Vepakomma
  • 26,870
  • 17
  • 81
  • 104
  • The linked question is newer than this one. Why then is this question closed as a duplicate of the newer question? – Dheeraj Vepakomma Apr 28 '23 at 04:39
  • 1
    Age is not a deciding factor in deciding which direction to close. The other question and its answers have been better received, and thus is generally considered the better close target. – Mark Rotteveel Apr 28 '23 at 09:04

9 Answers9

162

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • 4
    I'm sure most people know this but just to add: doing `list2 = list1.append('foo')` or `list2 = list1.insert(0, 'foo')` will result in `list2` having a value of None. Both `append` and `insert` are methods that mutate the list they are used on rather than returning a new list. – evantkchong Jul 28 '20 at 20:19
23

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

Iacks
  • 3,757
  • 2
  • 21
  • 24
  • This slice assignment insertion is faster than Raffe Kettler's list.insert(). See [Append a column to a 2 dimensional array](http://stackoverflow.com/questions/12537417/append-a-column-to-a-2-dimensional-array). Not that it usually matters. – ChaimG Jun 09 '15 at 21:30
16

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
9

best put brackets around foo, and use +=

list+=['foo']
Rik
  • 1,870
  • 3
  • 22
  • 35
5
>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']
mac
  • 42,153
  • 26
  • 121
  • 131
4

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']
Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
2

You have to add another list:

list[:0]=['foo']
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0
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']
Dheeraj Vepakomma
  • 26,870
  • 17
  • 81
  • 104
-2

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

list = list + ['foo']

Hope it helps!