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
Alternate range slicing in list (Python)
Slicing is used to extract a portion of a sequence (such as a list, tuple, or string) or other iterable objects. Python provides a flexible way to perform slicing using the slice notation with optional start, stop, and step parameters.
Syntax
list[start:stop:step]
What is Alternate Range Slicing?
Alternate range slicing retrieves elements from a list by skipping elements at a fixed interval using the step parameter. For example, if we want every second element from a list, we set step=2.
Basic Alternate Slicing
Example 1: Every Second Element
Extract every second element from the entire list ?
numbers = [1, 2, 3, 4, 5, 6] result = numbers[::2] print(result)
[1, 3, 5]
Example 2: Alternate Elements with Start and End
Perform alternate range slicing from a specific start and end position ?
cars = ["audi", "benz", "ciaz", "dodge", "etios", "ferrari", "g-wagon"] result = cars[1:6:2] print(result)
['benz', 'dodge', 'ferrari']
Using reversed() with Alternate Slicing
The reversed() function returns an iterator that accesses elements in reverse order. Combine it with alternate slicing to get elements in reverse alternate order ?
numbers = [1, 2, 3, 4, 5, 6] result = list(reversed(numbers[::2])) print(result)
[5, 3, 1]
Using range() and len() Functions
Use range() with len() to manually iterate through alternate indices ?
Syntax
range(start, stop, step)
- start: Starting position (default 0)
- stop: Stop position (usually len(list))
- step: Number of increments between sequences (use 2 for alternate elements)
Example
vehicles = ["activa", "BMW", "cd100", "ducati", "enfield", "fascino"]
result = []
for i in range(0, len(vehicles), 2):
result.append(vehicles[i])
print(result)
['activa', 'cd100', 'enfield']
Using enumerate() Function
The enumerate() function adds indices to iterable items. Use it to select elements based on even or odd indices ?
Syntax
enumerate(iterable, start)
Example
names = ["abhi", "bhanu", "chinna", "deepu", "esha", "farooq"]
alternate_names = []
for index, name in enumerate(names):
if index % 2 == 0:
alternate_names.append(name)
print(alternate_names)
['abhi', 'chinna', 'esha']
Comparison of Methods
| Method | Syntax | Best For |
|---|---|---|
| Basic Slicing | list[::2] |
Simple, readable code |
| range() + len() | range(0, len(list), 2) |
When you need indices |
| enumerate() | enumerate(list) |
Complex index-based conditions |
Conclusion
Use basic slicing [::2] for simple alternate element extraction. Use enumerate() when you need more control over index-based selection, and range() when building results programmatically.
