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
Selected Reading
Multiply Consecutive elements in a list using Python
In Python, multiplying consecutive elements in a list means creating pairs of adjacent elements and multiplying them together. This creates a new list with one less element than the original.
Basic Approach
The simplest method is to iterate through the list and multiply each element with the next one ?
def multiply_consecutives(numbers):
result = []
for i in range(len(numbers) - 1):
product = numbers[i] * numbers[i + 1]
result.append(product)
return result
# Example usage
numbers = [3, 6, 9, 12, 15]
output = multiply_consecutives(numbers)
print("Original list:", numbers)
print("Multiplied consecutives:", output)
Original list: [3, 6, 9, 12, 15] Multiplied consecutives: [18, 54, 108, 180]
Using List Comprehension
A more concise approach using list comprehension ?
def multiply_consecutives_compact(numbers):
return [numbers[i] * numbers[i + 1] for i in range(len(numbers) - 1)]
# Example usage
numbers = [2, 4, 6, 8, 10]
result = multiply_consecutives_compact(numbers)
print("Original list:", numbers)
print("Result:", result)
Original list: [2, 4, 6, 8, 10] Result: [8, 24, 48, 80]
Using zip() Function
An elegant solution using zip() to pair consecutive elements ?
def multiply_consecutives_zip(numbers):
return [a * b for a, b in zip(numbers, numbers[1:])]
# Example usage
numbers = [1, 3, 5, 7, 9]
result = multiply_consecutives_zip(numbers)
print("Original list:", numbers)
print("Consecutive products:", result)
Original list: [1, 3, 5, 7, 9] Consecutive products: [3, 15, 35, 63]
Handling Edge Cases
Always check for empty lists or lists with only one element ?
def safe_multiply_consecutives(numbers):
if len(numbers) < 2:
return []
return [numbers[i] * numbers[i + 1] for i in range(len(numbers) - 1)]
# Test with different cases
test_cases = [
[], # Empty list
[5], # Single element
[2, 3], # Two elements
[1, 2, 3, 4] # Multiple elements
]
for case in test_cases:
result = safe_multiply_consecutives(case)
print(f"Input: {case} ? Output: {result}")
Input: [] ? Output: [] Input: [5] ? Output: [] Input: [2, 3] ? Output: [6] Input: [1, 2, 3, 4] ? Output: [2, 6, 12]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Basic Loop | High | Good | Learning/debugging |
| List Comprehension | Medium | Better | Concise code |
| zip() Method | Medium | Best | Functional programming |
Conclusion
Use list comprehension for concise code or the zip() method for optimal performance. Always handle edge cases like empty lists. The time complexity is O(n) for all approaches.
Advertisements
