1

Iam a novice in Python .Python list cannot be amended in a loop . The output for this is unchanged array str1. Iam trying to make this list zero.This is a little strange for me . Why cant I change the elements of the list ?

 import re,string
 str1=["This is a review","This is not a review"]
 for each in str1:
    each=" "
 print str1

Any clue?

Pulkit Bhardwaj
  • 143
  • 1
  • 2
  • 11
  • In python List is type of object http://stackoverflow.com/questions/24292174/are-python-lists-mutable – Udit Kumawat Apr 19 '15 at 05:27
  • @Kasra, I would think this is more a duplicate of this question: http://stackoverflow.com/questions/14406449/modify-values-of-a-list-while-iterating-over-it-in-python – krock Apr 19 '15 at 05:33
  • @krock doesn't make much difference! questions like this have a lot of dup! :) – Mazdak Apr 19 '15 at 05:36
  • Guys we should use machine learning to better autosuggest similar topics . Semantic similarity and such . Just my two cents . – Pulkit Bhardwaj Apr 19 '15 at 05:54

2 Answers2

4

Here you are changing the local variable each and not the elements in the list. You can access the list by using enumerate to get the indexes:

for idx, each in enumerate(str1):
    str1[idx] = " "
krock
  • 28,904
  • 13
  • 79
  • 85
0

list are immutable. you cannot destroy the lest if thats what your trying to get at.

Franco Pettigrosso
  • 4,056
  • 2
  • 20
  • 32