Python for Loop
Python for loops repeat code. You can use it to repeat one or more lines of code.
- Python for loop is used to iterate over a sequence of items
- The for loop has the reserved keyword:
for
- The for-loop code is run for each element of the sequence
- You can end the for loop using the
break
statement - You can use
continue
statement to skip the the code in the for loop for an element - Python behaves more like an iterator
- For loops can iterate over Tuple, List, Set and String. They are all Python sequences.
- You can have nested for loops to iterate over a sequence of sequences
Related course: Complete Python Programming Course & Exercises
Python for Loop Syntax
The Python for loop syntax is simple for x in y:
. The in
operator is used to iterate over the elements in the sequence.
for element in sequence:
# code block
Python for Loop Examples
String
A for loop can loop over a string. It goes over a string character by character. The basic example below will output each character once.
for x in "hello":
print(x)
This makes no difference if you have a sentence, so the following will work too:
s = "Hello world, moon, universe"
for x in s:
print(f"char is {x}")
Tuple
A for loop can loop over a tuple. Every element of the tuple is in each reptition. For loops can be inside functions, in the example below the for loop is in the function lower_case()
.
def lower_case(my_tuple):
temp_list = []
for item in my_tuple:
temp_list.append(str(item).lower())
return tuple(temp_list)
fruits = ("Apple", "Orange", "LEMON")
fruits_new = lower_case(fruits)
print(fruits_new)
List
A for loop can loop over a list, this is another type of sequence. Like tulpe it goes over every element once.
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
Set
A for loop can loop over a set. It doesn't matter how many elements the set has. The set is created by calling the function set()
.
cities = set()
cities.add("Paris")
cities.add("Barcelona")
cities.add("Milano")
cities.add("Oslo")
cities.add("Bern")
for city in cities:
print(city)
Dictionary
A for loop can loop over a dictionary (A dictionary is a collection of key-value pairs). To loop over a dictionary you can use .items()
and grab the keys and values together.
my_dict = {"1": "Cat", "2": "Koala", "3": "Mouse"}
for k, v in my_dict.items():
print(f'Key={k}, Value={v}')
Using break Statement to Exit for Loop
You can use the reserved keyword break
to exit a loop. This exits the loop and continues the rest of the program. In generally you should avoid using break in loops.
messages = ["Aloha", "Hallo", "Exit", "Hasta la vista", "Sayonara"]
for msg in messages:
if msg == "Exit":
break;
print(f'Processing {msg}')
Python for Loop with continue Statement
The continue statement can be used to skip a cycle of the loop. If Python sees continue
, it will skip the current cycle and continue in the next cycle.
ints = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# process only odd numbers
for i in ints:
if i % 2 == 0:
continue
print(f'Processing {i}')
Python for loop with range() function
Range generates a list of numbers, this can be used to loop over numbers. This is practical when you want to loop over a fixed amount of numbers.
for i in range(5):
print("Processing for loop:", i)
for Loop with else statement
The else
keyword can be used in a loop. The program will go in the else clause when the loop has finished.
databases = ("PostgreSQL", "SQL Server","MySQL", "Oracle")
for db in databases:
print(f'Database is {db}')
else:
print("Finished processing list.")
Nested for Loops in Python
You can have nested loops (with tuples or lists). A nested loop is a loop inside a loop. This allows you to combine several collections.
list_tuples = [("Lemon", "Berry", "Melon"), ("Pear", "Guava", "Strawberry")]
for t_fruits in list_tuples:
for fruit in t_fruits:
print(fruit)
Reverse Iteration using for Loop and reversed() function
The function reversed()
turns a collection in reverse order. If you want to loop over a collection in reverse order, just call the reversed()
function.
numbers = (1, 2, 3, 4, 5)
for n in reversed(numbers):
print(n)