Lesson 5: For/While Loops and Comprehensions

In Python, loops are control flow structures that allow you to execute a code block repeatedly. There are two main types of loops: for loops and while loops.

--

for loop:

Both for in Python and foreach in PHP are used for iterating over elements in an array.

Python

streets = ['Abbey Road', 'Baker Street', 'Carnaby Street', 'Downing Street', 'Easy Street', 'Fleet Street']
 
for x in streets:
print(x)

PHP

$streets = ['Abbey Road', 'Baker Street', 'Carnaby Street', 'Downing Street', 'Easy Street', 'Fleet Street'];
 
foreach ($streets as $x) {
echo $x . "\n";
}

for with range() Function

In Python, the range() function is often used to generate a sequence of numbers, while in PHP, a more traditional for loop with initialization, condition, and increment is used.

Python

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

PHP

for ($i = 0; $i < 5; $i++) {
echo $i . "\n";
}

The range() function has two usage formats:

  • range(stop) - generates sequence from 0 to stop - 1.
  • range(start, stop[, step]) - generates sequence from start to stop - 1 with a step.
start = 10
stop = 100
step = 3
 
for x in range(start, stop, step):
print(x)

for with Dictionaries

When iterating dictionaries, you might notice that only keys are iterated by default:

d = {'a': 1, 'b': 2, 'c': 3}
 
for x in d:
print(x)
 
# a
# b
# c

If you want to iterate over the full items, use the items() method. It returns a list of tuples with key and value [('a', 1), ('b', 2), ('c', 3)]:

d = {'a': 1, 'b': 2, 'c': 3}
 
for key, val in d.items():
print(key, val)

If you wish to iterate only over values, use the values() dictionary method.

d = {'a': 1, 'b': 2, 'c': 3}
 
for val in d.values():
print(val)

while Loops:

The while loop syntax is quite similar in both Python and PHP languages and continues to execute code as long as the specified condition is true.

Python

count = 0
 
while count < 5:
print(count)
count += 1

PHP

$count = 0;
 
while ($count < 5) {
echo $count . "\n";
$count++;
}

Notice: Python doesn't have the increment operator ++. You need to re-assign the value like count = count + 1, and count += 1 is a shorthand for it.


Comprehensions

Comprehension in Python is a specific syntax for quickly creating data structures like lists, dictionaries, and sets.

Typically, in PHP, to generate an array containing squares of numbers from 0 to 9, you would do the following:

PHP

$results = [];
 
for ($i = 0; $i < 10; $i++) {
$results[] = $i * $i;
}
 
// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

By applying the same approach, you would likely write something like this in Python:

Python

results = []
 
for i in range(10):
s = i * i
results.append(s)
 
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Now, we can achieve the same goal using list comprehension with a single line of code.

results = [i * i for i in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

It can be read as: "Square each number in the range of 10.", as opposed to the previous example, you must dig into what is happening inside the loop.

To quickly summarize, you can create these comprehensions:

List comprehension

list_comp = [x * x for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Dictionary comprehension

dict_comp = {i: i * i for i in range(10) }
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Set comprehension

Set of possible unique remainders of dividing by 3 from 0 to 9.

set_comp = {i % 3 for i in range(10)}
# {0, 1, 2}

Generator comprehension

You can create your custom generators when using parenthesis with comprehension. This is not a tuple because it has a loop.

gen_comp = (2 * x + 5 for x in range(10))
 
for x in gen_comp:
print(x, end=" ")
 
# 5 7 9 11 13 15 17 19 21 23

Comprehensions with filtering

A comprehension pattern is often applicable when you want to filter out some values from data by adding an if condition at the end of the for loop.

names = ['John', 'Ricky', 'Paul', 'George', 'Bob', 'Ringo', 'Mick', 'Keith', 'Charlie', 'Bill']
 
filtered_names = [name for name in names if name[0] in 'RB']
# ['Ricky', 'Bob', 'Ringo', 'Bill']

That could be translated as "Get each name from names if the first letter is R or B".

These are the benefits of using comprehensions:

  • minimizes the amount of boilerplate code;
  • better readability (of course, if you don't abuse that);
  • comprehensions are often more efficient than loop-based constructs, and the interpreter is optimized for that;
  • helps to avoid unnecessary variables;
  • inline filtering;

Kwesi Odame Danquah avatar

list_comp = [x * i for x in range(10)]

for the above, i thik it is supposed to be list_comp = [x * x for x in range(10)]

Povilas avatar

Great catch! Fixed now.

Jibry Fathima Fasna avatar

I guess, this is supposed to be

Set of possible unique remainders of dividing by 3 from 0 to 9.

instead of

Set of possible unique remainders of multiplying by 3 from 0 to 9.

Povilas avatar

Of course, well noticed! Fixed now.