Newbie: adding string values to a list?

Duncan Booth duncan.booth at invalid.invalid
Wed Dec 21 10:23:44 EST 2005


planetthoughtful wrote:

> result = []
> for name in cursor.execute("SELECT name, address FROM contacts ORDER BY
> name"):
>     result.extend(name)
> 
> print result
> 
> For reasons I (obviously) don't understand, the "name" values get
> broken up into each individual letter of the values in the name field
> in the result list.
> 

Try interactive mode and it should be obvious:

>>> result = []
>>> result.extend('Fred')
>>> result
['F', 'r', 'e', 'd']
>>> result.append('Fred')
>>> result
['F', 'r', 'e', 'd', 'Fred']
>>> result.extend(['Fred'])
>>> result
['F', 'r', 'e', 'd', 'Fred', 'Fred']
>>> help(result.extend)
Help on built-in function extend:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the 
iterable

>>> 

in case it isn't obvious, the elements of a string are the individual 
characters, so the extend method will append the individual characters. Use 
the append method to put a single string on the end of a list.



More information about the Python-list mailing list