How to loop (iterate) through a list using for loop in Python

About 'for' loop in Python

In Python, the 'for' loop is used to iterate over a sequence or any iterable object such as a list, tuple, string, or range.

You can iterate over the elements of a list using 'for' loop.

About list in Python

In Python, list is a mutable sequence, typically used to store collections of items.

List can contain items of different data types, though it is typically used to store collections of homogeneous items.

In Python, list items are placed inside square brackets '[]' and items are separated with commas.

Elements of list can be iterated using 'for' loop.

Iterating over list elements using 'for' loop in Python

1. Create a list of fruit names (["Apple", "Banana", "Orange"]). Create a variable 'fruit_list' and assign the list to the variable (fruit_list = ["Apple", "Banana", "Orange"]).

2. Create a for loop with fruit_list object (for fruit in fruit_list:) where 'for' starts the loop, 'fruit' is a variable that represents an item of the fruit_list, 'fruit_list' is a list object, and the colon (:) is part of the syntax.

3. Now create a block of code that will be executed during each iteration of the for loop. The print message print(fruit) is the block of code to be executed. It will print each element of the fruit list.

Please take a closer look at the following example:

Example of for loop using list

Output of the above example
Apple
Banana
Orange

Live Code Playground

In the following Python code editor, you can practice by creating for loop to iterate over more lists. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output