Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Slicing a list which was converted from a string
    Hi, In python 3.3.3 converted a STRING to LIST and then tried to edit the list using slicing as below word="somebigword" list(word) word[4:7]=list("small") I get an error as below. Why does this happen, even though the String has been converted as a list in line 2. Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> word[4:7]=list('small') TypeError: 'str' object does not support item assignment However, if i do the following, it works fine. I want to understand the error in the previous case. word=list("somebigword") list(word) word[4:7]=list("small") The output is ['s', 'o', 'm', 'e', 's', 'm', 'a', 'l', 'l', 'w', 'o', 'r', 'd']
    zohaan posted this question on 12/27/13 | python, list, slice, converting
  • +
  • 2
  • -
  • Well, firstly in the first case you assing word as a string: word="somebigword" Next you say you list the word, and while this is true, you are not assigning it to the value of word itself. To do this, you would need to rephrase the code to: word=list(word) In the second code you posted, this words because the list is actually assigned to the value of word: word=list("somebigword") Again when you say list(word) it's not doing anything with the variable, it's simply running and returning true. The value assigned to the variable word is still the same. So in theory, you could use either of these bits of code: word="somebigword" word=list(word) word[4:7]=list("small") word=list("somebigword") word[4:7]=list("small")
  • +
  • 1
  • -
  • Thanks ninjex, understood now. This goes with the concept that strings are immutable in python I believe. In line 2 I am just displaying the string as a list and not actually converting the variable word to a list as you have pointed out in your answer.
    Log in to write an answer.