How to iterate over every two elements in a list with Python

2 Answers

0 votes
lst = [23, 89, 90, 17, 51, 19, 80, 90]

def pair(lst):
    itr = iter(lst)
    return zip(itr, itr)

for x, y in pair(lst):
   print(x, y)


 
 
 
'''
run:
 
23 89
90 17
51 19
80 90
 
'''

 



answered Jan 31, 2024 by avibootz
0 votes
lst = [23, 89, 90, 17, 51, 19, 80, 90]
 
# start, stop, step
for i in range(0, len(lst) - 1, 2):
    print(lst[i] , " ", lst[i + 1])
 
 

  
'''
run:
  
23 89
90 17
51 19
80 90
  
'''

 



answered Feb 1, 2024 by avibootz

Related questions

2 answers 225 views
2 answers 218 views
1 answer 165 views
1 answer 156 views
3 answers 202 views
...