Python - Looping Techniques

Basic Loops and Iteration

Python makes looping over variables extremely easy.

No matter the variable type, integers, a strings, lists, tuples and dictionaries, Python has a loop for that.

There are two types of loops in Python.

The For Loop
>>> x = 4
>>> y = 12
>>> for x in range(y):
...   print(x)
0, 1 , 2, 3, 4, 5, 6, 7, 8, 9, 10, 11  
>>> squares = []
>>> for x in range(11):
...  squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Using Range with Loops

The range(n) function yields the numbers 0, 1, … n-1, and range(a, b) returns a, a+1, … b-1. That is, up to but not including the last number. The combination of the for-loop and the range() function allow you to build a traditional numeric for loop:

>>> fruit = ['banana', 'apple', 'fig', 'squash']
>>> for fruit in range(len(fruit)):
...   print(fruit)
0, 1, 2, 3  #notice how it prints the indexes and not the values  
>>> # if I wanted the values, I can get them from the index
>>> for i in range(len(fruit)):
...  print(i, fruit[i])
0 banana  
1 apple  
2 fig  
3 squash     #now I have the index and the value  
Other Range functions
>>> def filter(x): return x % 3 ==0 or x % 5 ==0
...
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
>>> seq = range(8)
>>> def add(a, b): return x + y
...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
>>> def sum(seq):
...   def add(x, y): return x + y
...   return reduce(add, seq, 0)
...
>>> sum(range(1, 11))
55  
>>> sum([])
0  
The While Loop

The while loop will continue looping until a certain condition returns True. My favorite Python while loop is the Fibonacci sequence.

>>> fib_list = []
>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...       a, b = b, a + b
...       fib_list.append(a
...
>>> fib(10)
>>> fib_list
[1, 1, 2, 3, 5, 8, 13]

Craig Derington

Veteran full stack web dev focused on deploying high-performance, responsive, modern web applications using Python, NodeJS, Django, Flask, MongoDB and MySQL.

comments powered by Disqus