Skip to content
Related Articles

Related Articles

Python | Append Odd element twice

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 13 May, 2019

Given a list of number, the task is to create a new list from the initial list with the condition to append every odd element twice.

Below are some ways to achieve the above task.

Method #1: Using list comprehension




# Python code to create a new list from initial list
# with condition to append every odd element twice.
  
# List initialization
Input = [1, 2, 3, 8, 9, 11]
  
# Using list comprehension 
Output = [elem for x in Input for elem in (x, )*(x % 2 + 1)]
  
# printing 
print("Initial list is:'", Input)
print("New list is:", Output)

Output:

Initial list is:' [1, 2, 3, 8, 9, 11]
New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]

 
Method #2: Using itertools




# Python code to create a new list from initial list
# with condition to append every odd element twice.
   
# Importing
from itertools import chain
   
# List initialization
Input = [1, 2, 3, 8, 9, 11]
   
# Using list comprehension  and chain
Output = list(chain.from_iterable([i] 
              if i % 2 == 0 else [i]*2 for i in Input))
   
# printing 
print("Initial list is:'", Input)
print("New list is:", Output)

Output:

Initial list is:' [1, 2, 3, 8, 9, 11]
New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]

 
Method #3: Using Numpy array




# Python code to create a new list from initial list
# with condition to append every odd element twice.
  
# Importing
import numpy as np
  
# List initialization
Input = [1, 2, 3, 8, 9, 11]
Output = []
  
# Using Numpy repeat
for x in Input:
    (Output.extend(np.repeat(x, 2, axis = 0))
      if x % 2 == 1 else Output.append(x))
  
# printing 
print("Initial list is:'", Input)
print("New list is:", Output)

Output:

Initial list is:' [1, 2, 3, 8, 9, 11]
New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!