Python: For Loops

(Last Updated On: )

There are a variety of different ways to write a for loop in python. See below for different options. If you have any other suggestions please feel to add a comment.

Loop through a list one record at a time.

  1. for rec in data:
  2. #Do Something

Loop through a range of numbers up to 100.

  1. for i in range(100)
  2. #Do Something

Enumerate a list getting the index and value.

  1. for idx, value in enumerate(data):
  2. #Do Something

Inline for loop.

  1. d = [ x for x in data]

Inline for loop with an if condition.

  1. d = [ x for x in data if x==1]