Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: For every 2 items in list? [duplicate]

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?

like image 409
Doc Oliver Avatar asked Jun 25 '26 02:06

Doc Oliver


2 Answers

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)
like image 55
zdimension Avatar answered Jun 28 '26 01:06

zdimension


you can use:

for item in items[::2]:
   <your_code>
like image 36
kederrac Avatar answered Jun 28 '26 02:06

kederrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!