Question:
Making a class on Python regarding comprehension, when creating lists or dictionaries, they gave the following example:
>>> list = [i%2 for i in range(0,10)]
>>> list
And returned:
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
It is not clear to me in this case what the functionality of the %
operator is.
Could someone explain it?
Answer:
%
designates the modulus or remainder of the division.
- If you divide 15 by 2, you get 7 with a remainder of 1. That is, 15 = 7*2 + 1.
- If you divide 15 by 3, you get 5 with a remainder of 0. That is, 15 = 5*3.
In Python:
>>> 15 / 2
7
>>> 15 % 2
1
>>> 15 / 3
5
>>> 15 % 3
0
In your case, i%2
is dividing each element in the range between 0 and 9 by 2 and seeing what its remainder is, which would be equivalent to saying:
>>> for i in range(0, 10): print(i%2)
0
1
0
1
0
1
0
1
0
1
This concept is present in practically all programming languages and, as you saw, it is very practical when used in list comprehension.