Python Use a for Loop to Iterate Over All Elements in a List
In Python,for loop is a common way to iterate over list elements. Through the for loop, we can access each element in the list in turn and operate on it.
Example
Define a list
fruits
=
[
"apple"
,
"banana"
,
"cherry"
]
Use a for loop to iterate over the list
for
fruit
in
fruits:
(
fruit
)
Code analysis:
fruits = ["apple", "banana", "cherry"]: Define a list containing three elementsfruits。for fruit in fruits:: When usingforIterate over the listfruits, each iteration assigns one element of the list to the variablefruit。print(fruit): In each iteration, print the currentfruitvalue.
Output result:
apple
banana
cherry
Python3 Examples