Python Pair iteration in list (original) (raw)

Last Updated : 10 Dec, 2024

**Pair iteration involves accessing consecutive or specific pairs of elements from a list. It is a common task particularly in scenarios such as comparing neighboring elements, creating tuple pairs, or analyzing sequential data. Python provides several ways to iterate through pairs efficiently ranging from simple loops to using specialized libraries.

**Using zip() for Overlapping pairs

The zip() function is one of the most efficient ways to pair consecutive elements in a list. It combines slices of the list to create pairs.

Python `

a = [1, 2, 3, 4, 5]

Pair iteration using zip()

for x, y in zip(a, a[1:]): print((x, y))

`

Output

(1, 2) (2, 3) (3, 4) (4, 5)

**Explanation:

**We can also use zip() for Non-Overlapping pairs.

Python `

a = [1, 2, 3, 4, 5, 6]

Pair iteration using slicing and zip

for pair in zip(a[::2], a[1::2]): print(pair)

`

Output

(1, 2) (3, 4) (5, 6)

**Explanation:

**Let's explore some more methods for pair iteration in list.

Table of Content

**Using Index-Based Iteration

This method uses a for loop with an index to access pairs of consecutive elements. The loop runs from the first index to the second-to-last index pairing each element with the next. It is useful when indices are explicitly needed

Python `

a = [10, 20, 30, 40]

Pair iteration using indices

for i in range(len(a) - 1): print((a[i], a[i + 1]))

`

Output

(10, 20) (20, 30) (30, 40)

**Explanation:

**Using List Comprehension

A list comprehension can be used to generate all pairs of consecutive elements in a single line.The comprehension creates a new list of tuples containing consecutive pairs****.** This method is concise and suitable for scenarios where all pairs are needed as a single collection.

Python `

a = [5, 15, 25, 35]

Pair iteration using list comprehension

pairs = [(a[i], a[i + 1]) for i in range(len(a) - 1)] print(pairs)

`

Output

[(5, 15), (15, 25), (25, 35)]

**Explanation:

Similar Reads