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?
            Asked
            
        
        
            Active
            
        
            Viewed 3,903 times
        
    2
            
            
         
    
    
        Doc Oliver
        
- 31
- 1
- 3
- 
                    2Do you mean every other item, every non-overlapping pair, or every overlapping pair? – Davis Herring Aug 25 '19 at 22:14
5 Answers
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
0
            
            
        for idx, item in enumerate(items):
    if idx % 2 == 1:
        // do something
 
    
    
        greentec
        
- 2,130
- 1
- 19
- 16
- 
                    1Why not use the slice notation? `items[::2]` would be more Pythonic – zdimension Aug 25 '19 at 22:15
- 
                    Yes, if we don't need to access the index, that might be a better way. – greentec Aug 25 '19 at 22:17
- 
                    @zdimension: There is sometimes a reason to not copy (even half of) the input. – Davis Herring Aug 25 '19 at 22:26
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
