2

The default for loop only iterates through each item at a time. How can I make it so I can iterate through every 2 items?

Doc Oliver
  • 31
  • 1
  • 3

5 Answers5

4

You can use the slice notation:

for item in items[::2]:
   print(item)

If you want to iterate pairwise every 2 items, you can do this:

for item1, item2 in zip(items[::2], items[1::2]):
   print(item1, item2)
zdimension
  • 977
  • 1
  • 12
  • 33
1

you can use:

for item in items[::2]:
   <your_code>
kederrac
  • 16,819
  • 6
  • 32
  • 55
0
for idx, item in enumerate(items):
    if idx % 2 == 1:
        // do something
greentec
  • 2,130
  • 1
  • 19
  • 16
0

The following will iterate over every two items:

for i in range(0,20,2):
    print(i)
Neeraj Agarwal
  • 1,059
  • 6
  • 5
0

Assuming you are talking about a list. Then You can use the slice notation

data = [1,2,3,4,5,6]
for i in data[::2]:
...     print(I)

ardms
  • 158
  • 4
  • 16