Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Consecutive elements pairing in list in Python
During data analysis using Python, we may need to pair up consecutive elements of a list. This creates overlapping pairs where each element (except the first and last) appears in two pairs. Here are the most common approaches to achieve this.
Using List Comprehension with range()
We can use list comprehension with range() to iterate through consecutive indexes and pair adjacent elements ?
numbers = [51, 23, 11, 45]
# Given list
print("Given list:", numbers)
# Pair consecutive elements using list comprehension
result = [[numbers[i], numbers[i + 1]] for i in range(len(numbers) - 1)]
# Result
print("The list with paired elements:")
print(result)
Given list: [51, 23, 11, 45] The list with paired elements: [[51, 23], [23, 11], [11, 45]]
Using zip() with Slicing
The zip() function can combine the original list with its sliced version starting from index 1. This creates pairs of consecutive elements efficiently ?
numbers = [51, 23, 11, 45]
# Given list
print("Given list:", numbers)
# Use zip with slicing
result = list(zip(numbers, numbers[1:]))
# Result
print("The list with paired elements:")
print(result)
Given list: [51, 23, 11, 45] The list with paired elements: [(51, 23), (23, 11), (11, 45)]
Converting Tuples to Lists
If you need the pairs as lists instead of tuples, you can convert them using map() ?
numbers = [51, 23, 11, 45]
# Given list
print("Given list:", numbers)
# Use zip and convert tuples to lists
result = list(map(list, zip(numbers, numbers[1:])))
# Result
print("The list with paired elements:")
print(result)
Given list: [51, 23, 11, 45] The list with paired elements: [[51, 23], [23, 11], [11, 45]]
Comparison
| Method | Output Type | Performance | Readability |
|---|---|---|---|
| List comprehension | Lists | Good | Clear |
zip() |
Tuples | Best | Very clear |
zip() + map() |
Lists | Good | Moderate |
Conclusion
Use zip(numbers, numbers[1:]) for the most efficient and readable solution. Use list comprehension when you need more control over the pairing logic, and add map(list, ...) when you specifically need lists instead of tuples.
