You can go through by index and modify in place that way
for i, _ in enumerate(lines_list):
lines_list[i] = lines_list[i].strip()
though I think many would prefer the simplicity of duplicating the list if the list isn't so big that it causes an issue
lines_list = [line.strip() for line in lines_list]
The issue is using the =
operator reassigns to the variable line
, it doesn't do anything to affect the contents of the original string. New python programmers are equally as often surprised when:
for i in range(10):
print(i)
i += 1
prints the numbers 0,1,2,3,4,5,6,7,8,9. This occurs because the for loop reassigns i
at the beginning of each iteration to the next element in the range. It's not exactly your problem, but it's similar.
Since you are reading lines out of a file, and stripping them afterwards, really what you should do is
with open(file_name) as f:
lines_list = [line.strip() for line in f]
which reads and strips one line at a time, rather than reading everything first, then stripping the lines afterwards