Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.extend(string) adds every character instead of just the string

I am trying to extend an element to a list in Python, however, instead of extending the string in the index 'i' it extends every character of the string in the index 'i'.

For example I have a list called 'strings' with just a string 'string1' and an empty list called 'final_list'.

I want to extend the first element of 'strings' to the 'final_list', so I do final_list.extend(strings[0]). But instead of the 'final_list' to end with a length of 1, corresponding to the string inserted, the list ends up with a length of 7.

If it helps, this is my code:

con = connect()
    i = 0
    new_files = []
    while i < len(files):
        info_file = obter_info(con, files[i])
        if info_file [5] == 0: #file not processed
            new_files.append(files[i])
        i += 1

Does anyone know how can I make this to work?

like image 652
undisp Avatar asked Apr 29 '15 14:04

undisp


1 Answers

The extend method takes an iterable as an argument, unpacks that iterable and adds each element individually to the list upon which it is called. In your case, you are "extending" a list with a string. A string is an iterable. As such, the string is "unpacked" and each character is added separately:

>>> d = []
>>> d.extend('hello')
>>> print(d)
['h', 'e', 'l', 'l', 'o']

If you simply want to add one element of a list to another list, then use append. Otherwise, surround the string in a list and repeat the extend:

>>> d = []
>>> d.extend(['hello'])
>>> print(d)
['hello']
like image 95
paidhima Avatar answered Oct 08 '22 22:10

paidhima