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
Append Odd element twice in Python
Sometimes we need to process a list where odd numbers appear twice while even numbers remain unchanged. This is useful in data processing scenarios where odd values need special emphasis or duplication.
Using List Comprehension
The most concise approach uses list comprehension with conditional repetition ?
numbers = [2, 11, 5, 24, 5]
# Repeat odd numbers twice, keep even numbers once
result = [value for num in numbers for value in ([num] if num % 2 == 0 else [num, num])]
print("Original list:", numbers)
print("After processing:", result)
Original list: [2, 11, 5, 24, 5] After processing: [2, 11, 11, 5, 5, 24, 5, 5]
Using itertools.chain
The chain.from_iterable() method efficiently flattens nested iterables ?
from itertools import chain
numbers = [-1, -2, -9, -12]
# Create sublists based on odd/even condition, then flatten
result = list(chain.from_iterable([num] if num % 2 == 0 else [num, num] for num in numbers))
print("Original list:", numbers)
print("After processing:", result)
Original list: [-1, -2, -9, -12] After processing: [-1, -1, -2, -9, -9, -12]
Using Simple For Loop
A straightforward approach using a for loop for better readability ?
numbers = [9.0, 7.0, 5.0, 4.0]
result = []
for num in numbers:
if num % 2 == 1: # Odd number
result.extend([num, num])
else: # Even number
result.append(num)
print("Original list:", numbers)
print("After processing:", result)
Original list: [9.0, 7.0, 5.0, 4.0] After processing: [9.0, 9.0, 7.0, 7.0, 5.0, 5.0, 4.0]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | Medium | Fast | Compact solutions |
| itertools.chain | Medium | Very Fast | Large datasets |
| For Loop | High | Good | Learning/debugging |
Conclusion
Use list comprehension for compact code, itertools.chain for performance with large datasets, or simple for loops when readability is priority. All methods effectively duplicate odd numbers while preserving even numbers.
Advertisements
