One of these methods uses split() function while other methods convert the string into a list without split() function. Python list has a constructor which accepts an iterable as argument and returns a list whose elements are the elements of iterable. An iterable is a structure that can be iterated.
Adding a string to a list inserts the string as a single element, and the element will be added to the list at the end. The list. append() will append it to the end of the list.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With