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
Python – Alternate rear iteration
Alternate rear iteration means traversing a list from the end to the beginning while selecting every alternate element. Python provides several approaches using range(), slicing, and lambda functions to achieve this efficiently.
What is Alternate Rear Iteration?
In alternate rear iteration, we start from the last element of a list and move backwards, picking every second element. For example, in the list [1, 2, 3, 4, 5, 6, 8], we would get [8, 5, 3, 1].
Using range() with Negative Step
The range() function allows us to iterate backwards with a step of 2 to get alternate elements from the rear ?
# Initialize list with integer elements
numbers = [1, 2, 3, 4, 5, 6, 8]
alternate_list = []
# Iterate from the last index backwards with step -2
for i in range(len(numbers) - 1, -1, -2):
alternate_list.append(numbers[i])
print("Alternate rear iteration:", alternate_list)
Alternate rear iteration: [8, 5, 3, 1]
The range(len(numbers) - 1, -1, -2) starts from the last index, goes to 1 (before the first index), and steps by 2 to get alternate elements.
Using Slicing Method
Python's slicing with ::2 selects every alternate element, and reversed() reverses the order ?
# Initialize list
numbers = [1, 2, 3, 5, 7, 9, 4]
# Get alternate elements and reverse them
alternate_list = list(reversed(numbers[::2]))
print("Alternate rear iteration:", alternate_list)
Alternate rear iteration: [4, 7, 3, 1]
Here numbers[::2] gets elements at indices 0, 2, 4, 6, then reversed() reverses this sequence.
Using Lambda Function with Filter
Lambda functions can filter elements based on their index positions in a reversed list ?
# Initialize list
numbers = [1, 2, 3, 5, 7, 9, 4]
# Use lambda with filter to get alternate elements from reversed list
reversed_list = list(reversed(numbers))
alternate_list = [reversed_list[i] for i in range(0, len(reversed_list), 2)]
print("Alternate rear iteration:", alternate_list)
Alternate rear iteration: [4, 7, 3, 1]
Using Direct Slicing (Most Efficient)
The most concise approach uses negative indexing with slicing ?
# Initialize list
numbers = [1, 2, 3, 4, 5, 6, 8]
# Direct slicing from rear with step -2
alternate_list = numbers[::-2]
print("Alternate rear iteration:", alternate_list)
Alternate rear iteration: [8, 5, 3, 1]
Comparison of Methods
| Method | Code Length | Readability | Performance |
|---|---|---|---|
range() with loop |
Long | Clear | Slower |
reversed() + slicing |
Medium | Good | Medium |
Direct slicing [::-2]
|
Short | Excellent | Fastest |
Conclusion
Use [::-2] for the most efficient alternate rear iteration. For learning purposes, the range() approach helps understand the underlying logic of backward iteration with alternate elements.
