94,079 views
19 votes
19 votes
When i use for function the output is ['Banana', 'Orange']; However, when used if function the output is ['Apple', 'Banana', 'Orange']. Why?

foods = ["Apple", "Banana", "Pineapple", "Orange"]

removeFoods = foods[2]
for removeFoods in foods:
foods.remove(removeFoods)

print(foods)

________

foods = ["Apple", "Banana", "Pineapple", "Orange"]

removeFoods = foods[2]
if removeFoods in foods:
foods.remove(removeFoods)

print(foods)

User Thunderstriker
by
2.6k points

1 Answer

23 votes
23 votes

Answer:

Step-by-step explanation:

The difference in the output is due to the fact that the for loop is iterating over the list foods, while the if statement is only evaluating a single element in the list.

In the for loop, the variable removeFoods is being assigned the value of each element in the list in turn, and the foods.remove(removeFoods) line is being executed for each element. This means that the for loop will iterate over the entire list and remove all the elements except the last one.

In the if statement, the variable removeFoods is only being evaluated once, and the foods.remove(removeFoods) line is only being executed if removeFoods is in the list. Since removeFoods is equal to "Pineapple", and "Pineapple" is not in the list, the if statement does not execute and no elements are removed from the list.

So the difference in the output is due to the different ways that the two blocks of code are interacting with the list.

User Gauravphoenix
by
2.9k points