How can I change the list element using the for statement in Python?

Asked 2 years ago, Updated 2 years ago, 95 views

In Python, you want to change the element that meets the condition to a different value.

temp = ['apple', 'banana', 'coke']

for i in temp:
    if i == 'coke':
        i = 'grape'

print(temp)

I thought it would be "apple", "banana", "grave" but it didn't work.

temp = ['apple', 'banana', 'coke']
i = 0

for temp[i] in range(len(temp)):
    if temp[i] == 'coke':
        temp[i] = 'grape'

print(temp)

There's no problem if you do it like this way. Can't we change it to the first way?

python for list

2022-09-22 13:02

3 Answers

Let's take a look at fori in temp among these codes! It is a line that copy elements of temp one by one with i. In other words, it is concluded that the value cannot be changed in this way because the address (object) is not forwarded, but only the value is copied and forwarded.

If you want to use a code similar to that, try the following code. Of course, the code below is just an example, and there are many other good ways :)

temp = ['apple', 'banana', 'coke']

for i in temp:
    if (i == "coke"):
        temp[temp.index("coke")] = "grape"
        #temp.The index ("coke") looks for "coke" in the temp.
        #If there is a corresponding value, it returns the location of the value.

print(temp)


2022-09-22 13:02

I don't know why I have to do the first method, but in conclusion, I can't change it to the first method. Because the value of i is a copy of the element in the temp, even if you change the copied i value to 'grave', the original temp value does not change. The second method is to change the temp[i] value itself to 'grave', so the desired value is output.

a = 1, b = a, b = 2, It doesn't make a = 2...


2022-09-22 13:02

I think what you want is mapping.

temp = ['apple', 'banana', 'coke']

def no_soda(food) :
    return 'grape' if food is 'coke' else food
final_realfinal_ver333 = map(no_soda, temp)

# 3 lines above and 1 line below have the same function
# # final_realfinal_ver333 = map(lambda food: 'grape' if food is 'coke' else food, temp)

print(final_realfinal_ver333) # ['apple', 'banana', 'grape']


2022-09-22 13:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.