Search code examples
pythonlisttypeerrorswap

Problem when swapping python list entries


I have tried to do this:

A = [["test1"],["test2"]]
A[0][0], A[1][0] = A[1][0], A[0][0]

When executing print(A) the output is as expected: The two entries are swapped.

With this code however "TypeError: "str" object does not support item assignment" (line 8) is being raised:

import sys

try:
  with open ("Values", "r") as f:
    lines = f.readlines()
    for i in range(len(lines)):
      for j in range(len(lines[i])//2):  
        lines[i][j], lines[i][len(lines[i])-1-j] = lines[i][len(lines[i])-1-j], lines[i][j]

except FileNotFoundError:
  print("File could not be found.")

Solution

  • You essentially already answered your question. "python strings are not mutable" while lists are.

    See you can do

    l = ['a','b','c']
    l[0] = x
    # ['x','b','c']
    

    while you can't do

    l = 'abc'
    l[0] = x
    # TypeError: "str" object does not support item assignment
    

    And your line lines[i][j] tries to change one character in a string.

    Instead try converting the string to a list first. Then swapping the characters. Then converting it back to a string:

    temp = list(lines[i])
    temp[j], temp[len(lines[i])-1-j] = temp[len(lines[i])-1-j], temp[j]
    lines[i] = "".join(temp)