Skip to content

Python for in loop

  • by

Python for-in loop is used to iterate over a sequence of numbers, a string, a list, a tuple, or a dictionary.

for val in sequence:
    loop body

Python for in loop

Simple example code where for loop does not require an indexing variable to set beforehand. Let’s write the Program to find the sum of all numbers stored in a list.

# List of numbers
numbers = [1, 2, 3, 8, 4, 2, 5, 4]
sum = 0

# iterate over the list
for val in numbers:
    sum = sum + val

print("The sum is", sum)

Output:

Python for in loop

More examples

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Looping Through a String

for x in "Hello":
  print(x)

With the break statement, you can stop the loop before it has looped through all the items:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

Comment if you have any doubts or suggestions on this Python loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading