126

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
  • 19,992
  • 13
  • 70
  • 98

9 Answers9

161

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')
Rafe Kettler
  • 73,388
  • 19
  • 151
  • 149
  • 3
    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
22

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,629
  • 2
  • 20
  • 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
  • 22,918
  • 12
  • 67
  • 88
8

best put brackets around foo, and use +=

list+=['foo']
Rik
  • 1,710
  • 2
  • 20
  • 31
5
>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']
mac
  • 40,746
  • 24
  • 119
  • 129
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
  • 13,966
  • 5
  • 51
  • 72
2

You have to add another list:

list[:0]=['foo']
Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
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
  • 19,992
  • 13
  • 70
  • 98
-2

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

list = list + ['foo']

Hope it helps!