Explain Codes LogoExplain Codes Logo

How do I loop through a list by twos?

python
list
loop
iterators
Alex KataevbyAlex Kataev·Feb 12, 2025
TLDR

To loop through a list by twos using a for loop in conjunction with range with a step of 2, you can employ the following code:

my_list = [1, 2, 3, 4, 5, 6] for i in range(0, len(my_list), 2): # Grabbing those pairs, but what if the list is odd-length? No worries! pair = my_list[i:i+2] print(tuple(pair))

This provides tuples of pairs: (1, 2), (3, 4), (5, 6), and can handle lists with an odd number of elements gracefully.

Optimize Performance in Python 2 with xrange

For those dinosaur lovers and their Python 2, xrange is your best bet. This create an xrange object, making your loop more memory-friendly.

for i in xrange(0, len(my_list), 2): # Loops like a T-Rex! Rawr! print(my_list[i:i+2])

Sue Chef's Recipe: List Slicing

With the aid of list slicing syntax L[start:stop:step], you can cut through the list like a pro chef!

for pair in my_list[::2]: #Sharpen your slicing skills! print(pair)

While this prints every second element of my_list, it doesn't generate pairs. Why? Maybe it's a pacifist?

Zipping Pairs

Ever tried zipping a pair of mismatched socks? Let's do it in Python with zip:

for left_sock, right_sock in zip(my_list[::2], my_list[1::2]): # make them get along like mismatched socks! print(left_sock, right_sock)

itertools for Advanced Paring

itertools, the bionic Swiss Army knife of Python, can be employed for more complex pair handling:

from itertools import izip for a, b in izip(*[iter(my_list)]*2): # like a Swiss Army knife on steroids print(a, b)

This will pair up elements from my_list using that izip magic!

Handy-dandy Iterable Objects

Both range and xrange generate iterable objects, not lists, making them particularly beneficial for large lists where memory efficiency is crucial.

Manual Indexing for Full Control

Wanting more control over your loop logic? Just do it manually with a while loop:

i = 0 while i < len(my_list) - 1: # Manually driving the loop around! print(my_list[i], my_list[i+1]) i += 2

Dealing with Different Length Lists

The zip_longest function from itertools pairs elements like a champ when lists are of uneven length, making it fit for Python 3.

Fine-tuning Performance and Memory

Among these methods, weigh in on both performance and memory usage. For instance, range() and xrange() are beneficial for loops that don't need lists of indices.

Manual Loops for Exceptional Cases

A while loop with manual indexing allows you flexibility when the residual items in an odd-length list need special treatment or when exceptional cases surface within the loop.

Grouper: A Reusable Solution

Here's the grouper function handy to chunk up arbitrary group sizes. It's even part of the itertools recipes!

from itertools import zip_longest # iter = my favorite iterable def grouper(iterable, n, fillvalue=None): # Packed lunch for your loops args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)

This function is reusable and decked out to improve the readability of your code.

Striking A Balance

Ultimately, Pythonic coding highlights simplicity and expressiveness. List slicing, for instance, is an elegant solution for simple cases. However, when a more intricate problem arises, feel free to explore other methods.