Bootstrap FreeKB - Python (Scripting) - Looping over a list
Python (Scripting) - Looping over a list

Updated:   |  Python (Scripting) articles

Here is probably the most basic way to loop through the items in a list in Python.

#!/usr/bin/python3
for item in ["apple", "banana", "orange", "grapes"]:
  print(item)

 

This should print each item in the list.

apple
banana
orange
grapes

 

However, it's more common to store the items in a list.

#!/usr/bin/python3
fruits = ["apple", "banana", "orange", "grapes"]
for item in fruits:
  print(item)

 

This should print each item in the list.

apple
banana
orange
grapes

 

You can loop through the list in reverse order.

#!/usr/bin/python3
fruits = ["apple", "banana", "orange", "grapes"]
for item in reversed(fruits):
  print(item)  

 

This should print each item in the list in reverse order.

grapes
orange
banana
apple

 

You can loop through a list that contains variables.

#!/usr/bin/python3
foo = "Hello"
bar = "World"

for item in [foo, bar]:
  print(item)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f003d8 in the box below so that we can be sure you are a human.