Search code examples
pythonlistupdating

Update elements of a list


Why aren't the elements updated within the for-loop? This gets me

met_dir = r'D:\09052012\run\fout'
out_dir = r'D:\inpassingstest\test_cmd'

for c_dir in [met_dir,out_dir]:
    if c_dir[-1:] != '\\':
       c_dir += '\\'
       print c_dir
print met_dir

>>>D:\09052012\run\fout\
>>>D:\inpassingstest\test_cmd\
>>>D:\09052012\run\fout

Same happens when I use a index to address the elements.


Solution

  • Strings are immutable objects, that is, you cannot change it, instead making new strings. This means that when you append to the string, the original remains unchanged. The easy solution to this is a list comprehension, to make a new list of the new strings:

    >>> [c_dir + "\\" if not c_dir.endswith("\\") else c_dir for c_dir in (met_dir, out_dir)]
    ['D:\\09052012\\run\\fout\\', 'D:\\inpassingstest\\test_cmd\\']
    

    Which one can easily unpack back into the values:

    met_dir, out_dir = [...]
    

    Note my use of str.endswith() which is a nice way of doing the check.