pythonstringjoin

Why does `str.join` not modify the list in-place?


I had a bug that I reduced down to this:

a = ['a','b','c']
print( "Before", a )
" ".join(a)
print( "After", a )

Which outputs this:

runfile('C:/program.py', wdir=r'C:/')

Before ['a', 'b', 'c']
After ['a', 'b', 'c']

What's going on here?


Solution

  • str.join does not operate in-place because string objects are immutable in Python. Instead, it returns an entirely new string object.

    If you want a to reference this new object, you need to explicitly reassign it:

    a = " ".join(a)
    

    Demo:

    >>> a = ['a','b','c']
    >>> print("Before", a)
    Before ['a', 'b', 'c']
    >>> a = " ".join(a)
    >>> print("After", a)
    After a b c
    >>>