In C/C++, I can have the following loop
for(int k = 1; k <= c; k += 2)
How do the same thing in Python?
I can do this
for k in range(1, c):
In Python, which would be identical to
for(int k = 1; k <= c; k++)
in C/C++.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.
This is actually faster than using the above code with range(), and removes the extraneous
ivariable.If you need to edit items of a list in-place, then you do need the index, but there’s still a better way:
Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.