Python: list items are not changed in for loop

前端 未结 3 2024
無奈伤痛
無奈伤痛 2020-12-12 07:33

I was shocked when the following code did not do what I expected it to do:

lines_list = [\'this is line 1\\n\', \'this is line 2\\n\', \'this is line 3\\n\']         


        
3条回答
  •  悲哀的现实
    2020-12-12 08:15

    In your example, line is simply a variable. It is not connected to the list, where it might come from. Think of the problems, that would occur, if every variable modifies its origin!

    In python, lists normally are not modified but a new one is created. Therefore there is something called list comprehension:

    lines_list = [line.strip() for line in lines_list]
    

提交回复
热议问题