News How to use For Loops in Python

bit_user

Titan
Ambassador
Heh, you forgot a couple things: continue and else.


Yes! You can use else with for loops! So, instead of writing:
Code:
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:
Code:
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.
 
Last edited:

bit_user

Titan
Ambassador
Also, you could include a brief example of list comprehensions:
Code:
l = [ i * 2 for i in range(5) ]

Which is equivalent to: l = [ 0, 2, 4, 6, 8 ].

For more:

 

bit_user

Titan
Ambassador
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: