I'm trying to iterate over a list and change its values with a "for in" loop:
example_string = "This is a string."
for char in example_string :
char = 'r'
example_list = list(example_string)
for char in example_list:
char = 'r'
The string object is not modified by the iteration.
Does the "for in" iteration in Python returns another variable and not the actual list/string element?
I tried doing it with lists. I expected that the items in the list or string would get changed by the assignment.
CodePudding user response:
You can change in a list, but use the index instead:
example_string = ["This is a string.", "This is another string"]
for i in range(len(example_string)):
example_string[i] = "r"
print(example_string)
In your example, only the variable would change:
example_string = "This is a string."
for char in example_string:
char = 'r'
print(char)
You can select from your string using the index as well, however the string itself is immutable and you can't reassign directly in it:
Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.
CodePudding user response:
Yes its definitely possible with a for loop but you are not changing the original variable: example_string in your code. Try creating a new list and append or insert the new value in every iteration.
CodePudding user response:
Try defining a function in which you create a new list (or string) and append the changed elements in your for-in loop. An example of what I mean:
def change_in_list(_list):
new_list = []
for element in _list:
element = 'CHANGED'
new_list.append(element)
return new_list
example_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(example_list)
print(change_in_list(example_list))
For a string you would use
def modify_string(_string):
new_string = ''
for character in _string:
character = 'CHANGED'
new_string = character
return new_string
example_string = 'Hello World'
print(example_string)
print(modify_string(example_string))
The output here is string output
Both can be modified/adapted to your needs but I hope this helps