How to use For Loops in Python

How To Use For Loops in Python
(Image credit: Tom's Hardware)

In programming, for loops are incredibly versatile tools to repeat a section of code. For loops can loop for a set number of times using a range, they can have clauses / conditions which will end the loop and we can use them to iterate over items in a dictionary, list or tuple.

In this how to, we will show you how to get started with for loops using Python, the same syntax will also work with MicroPython and CircuitPython on boards such as the Raspberry Pi Pico.

Latest Videos FromTom's Hardware
Les Pounder
Associate Editor

Les Pounder is an associate editor at Tom's Hardware. He is a creative technologist and for seven years has created projects to educate and inspire minds both young and old. He has worked with the Raspberry Pi Foundation to write and deliver their teacher training program "Picademy".

  • bit_user
    Heh, you forgot a couple things: continue and else.
    https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

    Yes! You can use else with for loops! So, instead of writing:
    if my_list:
    for element in my_list:
    # do something with each element

    else:
    # do something in case of empty list

    You can simply write:
    for element in my_list:
    # do something with each element
    else:
    # do something in case of empty list

    Cool story: I once suggested this feature. Guido, himself, actually shot it down. Then, like 10 years later, I noticed it had been added! I don't know if Guido changed his mind, or maybe it just got suggested again and with a different outcome.
    Reply
  • bit_user
    Also, you could include a brief example of list comprehensions:
    l =
    Which is equivalent to: l = .

    For more:
    https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
    Reply
  • bit_user
    Lastly, you could also mention the builtin functions which do iteration and can often be used instead of loops:
    Reductions: all(), any(), min(), max(), and sum()enumerate()filter()map()zip()
    See:
    https://docs.python.org/3/library/functions.html
    Reply