Python List For Loop


Python List For Loop

Python List is a collection of items. For loop can be used to execute a set of statements for each of the element in the list.

https://youtu.be/s1-VeZhZvPg?si=X2lIqs-H5lGEcVWU

In this tutorial, we will learn how to use For loop to traverse through the elements of a given list.

Syntax of List For Loop

In general, the syntax to iterate over a list using for loop is

for element in list:
    statement(s)

where

  • element contains value of the this element in the list. For each iteration, next element in the list is loaded into this variable.
  • list is the Python List over which we would like to iterate.
  • statement(s) are block are set of statement(s) which execute for each of the element in the list.

Examples

1. Iterate over List using For Loop

In this example, we take a list of strings, and iterate over each string using for loop, and print the string length.

Python Program

myList = ['pineapple', 'banana', 'watermelon', 'mango']

for element in myList:
    print(len(element))

Output

9
6
10
5

Reference tutorials for the above program

2. Iterate over list of numbers using For loop

In this example, we will take a list of numbers, and iterate over each number using for loop, and in the body of for loop, we will check if the number is even or odd.

Python Program

myList = [5, 7, 8, 3, 4, 2, 9]

for element in myList:
    if element % 2 == 0:
        print('even')
    else:
        print('odd')

Output

odd
odd
even
odd
even
even
odd

Reference tutorials for the above program

Summary

In this tutorial of Python Examples, we learned how to use For Loop to iterate over Python List elements.