Reputation: 41
I'm wondering what the following is evaluating to on each iteration, I've checked the internet but can't find any definite answers
And also if there's anymore efficient ways to do it.
for i in range(0, len(c)):
if i & True:
pass
Upvotes: 0
Views: 66
Reputation: 106533
True
has an integer value of 1
in Python, so when the loop iterates an integer i
from 0
to the length of c
and performs bitwise-and on i
and 1
, it effectively checks if i
is an odd number and if so, executes the pass
statement (where I believe there are more code in your real code).
As for a more efficient way to do it, instead of generating all the numbers between 0 and the length of c
and filtering out even numbers, you can use the step
parameter of the range
function to generate the desired sequence of odd numbers in the first place:
for i in range(1, len(c), 2):
pass
Upvotes: 3
Reputation: 5210
i & True
evaluates to 0
for even numbers and 1
for odd numbers.
for i in range(0, 5):
print(i, i & True)
yields:
(0, 0)
(1, 1)
(2, 0)
(3, 1)
(4, 0)
Upvotes: 1