Iterations with python

Loop

for in statement: iterate over any sequences

The sequence can be a list,a string,a tuple and so for…
in python this statement is very very very common.
In fact for most of things we need to iterate we will use the for in statement.
but as everything is not a sequence we generally need to transform them into sequences.

Loop with a numeric range

With the range() function,we have multiple ways:

# iterate from 0 to 2:
for i in range(3):
print("We're at time %d" % i)
 
# same thing but with a final step
for i in range(3):
print("We're at time %d" % i)
else:
print("final value is %d " % i)
 
# iterate from 2 to 9
for i in range(2, 10):
print("We're at time %d" % i)
 
# iterate from 0 to 9 with a step of 3 (0,3,6,9)
for i in range(0, 10, 3):
print("We're at time %d" % i)

loop on natural sequences

on a list:

elements = ['dog', 'chicken', 'cat']
for e in elements:
	print(e, len(e), 'chars')

loop to have both the index and the value of the sequence

we can achieve it with enumerate(): a function returning a sequence under the hood

for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)

output:

0 tic
1 tac
2 toe

loop on dictionary

the items() function allows to iterate both on the key and the value:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)

output:

gallahad the pure
robin the brave

the keys() function allows to iterate on the keys:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for key in knights.keys():
    print(key)

output:

gallahad
robin

the values() function allows to iterate on the values:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for value in knights.values():
    print(value)

output:

the pure
the brave

while loop

i = 10
while i >= 5:
    print(i)
    i -= 1

To loop over two or more sequences at the same time: zip()

technically, zip() returns an iterator of tuples.
important:
in the case of the sequences don’t have the same length : the iteration finishes as soon as the any of them is exhausted.
example:

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail']
for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))

output:

What is your name?  It is lancelot.
What is your quest?  It is the holy grail.

loop in reverse on a sequence

for i in reversed(range(5)):
    print(i)

output:

4
3
2
1
0

loop in sorted order on a sequence

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for i in sorted(basket):
    print(i)

output:

apple
apple
banana
orange
orange
pear

other ways to use the sorted() function in a loop:

– sort in reverse order:
to do that we specify the reverse attribute of the function

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for i in sorted(basket,reverse=True):
    print(i)

– specify the key to sort the elements:
to do that we specify the key attribute of the function
for example here we sort tuples by their values:

foo_tuple = {
    'John': 50,
    'David': 40,
 
}
sorted_keys = sorted(foo_tuple, key=foo_tuple.get)
print(f'sorted_keys={sorted_keys}')

output:

sorted_keys=['David', 'John']
Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *