# For loops

A for loop starts with a 'for element in list:' definition that ends with a colon, followed by an intended block of commands of what to do with each element. The loop commands end with the end of the intended block. In Python loops are better replaced by List Comprehension.

# Loop over all elements of a list

mylist = ['A','B','C']

for element in mylist:

print(element)

# getting both element and it's index i (starting with 1)

mylist = ['A','B','C']

for i, element in enumerate(mylist,1):

print(i,element)

(1, 'A')

(2, 'B')

(3, 'C')

# same, but using list index over all elements

mylist = ['A','B','C']

for i in range(len(mylist)):

element = mylist[i]

print(i+1, element)

# print numbers 1..10

for i in range(1,11):

print(i)

# print 3 times 'Hello'

for i in range(3) :

print('Hello')

Hello

Hello

Hello

# loop over a list of number

datalist=[5,2,3]

for i in range(len(datalist)):

datalist[i]= 5 * datalist[i] # multiply each number by 5

print(datalist[i])

25

10

15

loop over two (or more) parallel lists (ends when shortest list is finished)

list1 = ['A','B','C','D']

list2 = ['a','b','c']

for (s1,s2) in zip(list1,list2):

print(s1 + s2)

Aa

Bb

Cc

using enumerate with zip to get also an index i

listA = ['a1', 'a2', 'a3']

listB = ['b1', 'b2', 'b3']

for i, (a, b) in enumerate(zip(listA, listB),1):

print(i, a, b)

(1, 'a1', 'b1')

(2, 'a2', 'b2')

(3, 'a3', 'b3')

sorted loop over two 'zipped' lists, sorted by the first list

>>> listN = [ 7 , 3 , 4 ]

>>> listS = ['a', 'b', 'c']

>>> for (n, s) in sorted(zip(listN,listS)):

print(n, s)

(3, 'b')

(4, 'c')

(7, 'a')

Or the same, but get directly the sorted list:

Sorting a list based on values of another list

>>> [s for (n, s) in sorted(zip(listN,listS))]

['b', 'c', 'a']

break to stop a loop

for i in [1,2,3,4,5]:

if i > 3:

break

print(i)

1

2

3