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']
for line in lines_list:
line = line.strip()
I of course expected each item in the list to become "stripped", i.e. in this case, to be free of the trailing '\n' char, but it did not...
print lines_list
The output:
['this is line 1\n', 'this is line 2\n', 'this is line 3\n']
So as you can guess, my question is if there is an elegant way to change the list items during the for loop? I don't want to duplicate the list...
EDIT:
I wanted to mention that by the way, in Perl or in Java, my usage works well. Python is the one with the unique behavior
In Java this will work:
String[] lines = {"this is line 1\n", "this is line 2\n", "this is line 3\n"};
for (String line : lines) {
line = line.trim();
}
In Perl this will work:
my @lines = ("this is line 1\n", "this is line 2\n", "this is line 3\n");
foreach my $line (@lines) {
$line =~ s/\s+$//;
$line =~ s/^\s+//;
}
lineseither, for the same reason the python example doesn't repl.it/@RyanHaining1/UntruePowderblueDifference - Ryan Hainingline = line.trim()to affect the reference that's in the array - SomethingSomethinglineto reference a new string. Even with a mutable type,=won't change the object on the left side,[]=is different. - Ryan Haining