Python uses for loop to iterate over all elements in a list

Document 对象参考手册Python3 Example

In Python,forloops are a common way to iterate over list elements. Throughfora loop, we can access each element in the list in sequence and operate on it.

Example

# Define a list
fruits = ["apple", "banana", "cherry"]

# Use a for loop to iterate through the list
for fruit in fruits:
    print(fruit)

Code analysis:

  1. fruits = ["apple", "banana", "cherry"]: define a list containing three elementsfruits。
  2. for fruit in fruits:: useforloop to iterate through the listfruits, each iteration assigns an element from the list to a variablefruit。
  3. print(fruit): in each loop iteration, print the currentfruitvalue.

Output result:

apple
banana
cherry

Document 对象参考手册Python3 Example

Other extensions