0

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
8
  • 1
    The & is a bitwise operator. Commented May 3, 2019 at 23:12
  • Are you asking what the code is doing? Because that code is not doing anything except counting from 0 to c. The if i & True: is equivalent to writing if i:. In the greater context of the loop, i will evaluate to True for non-zero, so you could rewrite the loop as for i in range(1, len(c)): Commented May 3, 2019 at 23:13
  • @TomLubenow no sorry i mean what's it evaluating to, code will be included within it Commented May 3, 2019 at 23:15
  • 2
    @TomLubenow You're thinking of i and True. & is a bit-wise operator, not a logical operator. Commented May 3, 2019 at 23:19
  • 1
    @TomLubenow no @ Barman is correct as i will evaluate to true if it’s 1 or false if it’s 0 Commented May 4, 2019 at 18:42

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.