Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a for Loop to Iterate Over All Elements in a List

Python Use a for Loop to Iterate Over All Elements in a List

Document Object Reference Manual Python3 Examples

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:

   

print

(

fruit

)

Code analysis:

  1. fruits = ["apple", "banana", "cherry"]: Define a list containing three elements fruits。
  2. for fruit in fruits:: When using for Iterate over the list fruits, each iteration assigns one element of the list to the variable fruit。
  3. print(fruit): In each iteration, print the current fruit value.

Output result:

apple
banana
cherry

Document Object Reference Manual Python3 Examples