Reputation: 11
I'm doing the Automate the Boring Stuff with Python Book and am on page 139. I have to make a program to add a '*' in front of each line. However, my for loop doesn't seem to work here.
rawtextlist = [
'list of interesting shows',
'list of nice foods',
'list of amazing sights'
]
for item in rawtextlist:
item = '*' + item
My output is as such below. I am missing the '*' character in front of each line when using the code above.
list of interesting shows
list of nice foods
list of amazing sights
The answer provided in the book is as such.
for i in range(len(rawtextlist)):
rawtextlist[i] = '*' + rawtextlist[i]
The program only works for the answer provided in the book and not my for loop. Any help would be greatly appreciated!
Upvotes: 0
Views: 174
Reputation: 140188
Here:
item = whatever_happens_doesnt_matter()
The reference that item
bears is created and thrown away in the first case and is not the same as the one in the original list (variable name is reassigned). And there's no way to make it work since strings are immutable anyway.
That's why the book has to use the very unpythonic for .. range
and indexing the original list construct to be sure to assign back the proper string reference. Terrible.
A better & more pythonic way would be to rebuild the list using list comprehension:
rawtextlist = ['*'+x for x in rawtextlist]
More on list comprehension method here: Appending the same string to a list of strings in Python
Upvotes: 1
Reputation: 2792
the parameter item
which you declared in the for loop is a new variable which each time holds a reference to the next string in the array.
Actually, what you are doing inside the loop is redefine the variable item
to point on a new string and this is not what you want (you don't change the string in the list, you just create new string and save it to at temporary variable).
You can either go with the program that provided or create new list with the updated strings like this:
new_list = []
for item in rawtextlist:
new_list.append('*' + item)
print(new_list)
or in one-line solution:
new_list = ['*' + item for item in rawtextlist]
print(new_list)
In addition, strings are immutables so I recommend you to look on this question and answer: Aren't Python strings immutable? Then why does a + " " + b work?
Upvotes: 0