Looping lists

In [ ]:
my_list = [1, 2, 3, 4, 'Python', 'is', 'neat']
for item in my_list:
    print(item)

break

Stop the execution of the loop.

In [ ]:
for item in my_list:
    if item == 'Python':
        break
    print(item)

continue

Continue to the next item without executing the lines occuring after continue inside the loop.

In [ ]:
for item in my_list:
    if item == 1:
        continue
    print(item)

enumerate()

In case you need to also know the index:

In [ ]:
for idx, val in enumerate(my_list):
    print('idx: {}, value: {}'.format(idx, val))

Looping dictionaries

In [ ]:
my_dict = {'hacker': True, 'age': 72, 'name': 'John Doe'}
for val in my_dict:
    print(val)
In [ ]:
for key, val in my_dict.items():
    print('{}={}'.format(key, val))

range()

In [ ]:
for number in range(5):
    print(number)
In [ ]:
for number in range(2, 5):
    print(number)
In [ ]:
for number in range(0, 10, 2):  # last one is step
    print(number)