-3

How do you append a string to a list of strings, particularly, to a specific string in the list?

For example:

myList = ['apples', 'oranges', 'bananas']

newString = 'peach'

I want to append newString to index 1 ('oranges') of myList (so that the newString appears after index 1 in myList.) How would I go about doing that?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • possible duplicate of [Insert an element at specific index in a list and return updated list](http://stackoverflow.com/questions/14895599/insert-an-element-at-specific-index-in-a-list-and-return-updated-list) – taesu Mar 02 '15 at 20:16
  • next time, please search before posting a question. – taesu Mar 02 '15 at 20:16

4 Answers4

5

Use list.insert:

In [3]: myList = ['apples', 'oranges', 'bananas']

In [4]: myList.insert(1, 'peach')

In [5]: myList
Out[5]: ['apples', 'peach', 'oranges', 'bananas']

1 is the position, 'peach' is the element to insert.

vaultah
  • 44,105
  • 12
  • 114
  • 143
4

There are two common ways to do this.

  1. Use list.insert method, like this

    >>> myList.insert(1, newString)
    >>> myList
    ['apples', 'peach', 'oranges', 'bananas']
    
  2. Use slicing to assign an element to the slice 1:1, like this

    >>> myList[1:1] = [newString]
    >>> myList
    ['apples', 'peach', 'oranges', 'bananas']
    

Quoting the documentation,

s.insert(i, x) same as s[i:i] = [x]

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

There is an inbuilt method for lists known as .insert() which takes 2 arguments , first being the position and the other the object you want to insert, So the code may look like:

myList = ['apples', 'oranges', 'bananas']

newString = 'peach'

position = 1

myList.insert(position, newString)
ZdaR
  • 22,343
  • 7
  • 66
  • 87
1

Just use the list.append method:

myList.append('X')
vaultah
  • 44,105
  • 12
  • 114
  • 143
Amrita Sawant
  • 10,403
  • 4
  • 22
  • 26