How can I write a python loop to count every other index? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I write a python loop to count every other index?

I want to write a python code that outputs the following 1 2 3 4 I tried this: For I in range(2): Print(I, I+1) But this outputs 0 1 1 2 So it does not work for me. How can I fix the loop? The goal of this loop is to go 1000 times to generate those kind of numbers.

7th Jun 2021, 10:27 PM
Karzan
5 Answers
+ 1
just in case you wanted to get a little fancier. y = [{a, a+1} for a in range(1, 50, 2)] print(y) the code is a list comprehension that creates a set 1, 2 etc. and the range starts at 1 to 50 or any number you want and skips every other number. you can change the set {} to a list [], tuple (), or just print. y = [print(a, a+1) for a in range(1, 50, 2)]
8th Jun 2021, 12:19 AM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 1
Yes loop counter should be incremented by 2 for each iteration 🤭
9th Jun 2021, 12:18 PM
Sanjay Kamath
Sanjay Kamath - avatar
0
Andrew your solution will break every third index. If you run the code the answer will be [(1, 2), (3,4), (5,6) ,(8,7)] as you see the third index must be 7,8 not 8,7.
8th Jun 2021, 6:20 PM
Karzan
0
Karzan i didnt run into that problem when i ran the code. have you tried to run the code? if so, do you mind sharing it?
9th Jun 2021, 4:11 AM
you are smart. you are brave.
you are smart. you are brave. - avatar
- 2
Actually I solved it: for i in range(2): if i % 2 ==0: Print(i, i+1) else: print(i+1, i+2)
7th Jun 2021, 10:36 PM
Karzan