Append Odd element twice in Python

PythonServer Side ProgrammingProgramming

In this article we will see how to take a list which contains some odd numbers as its elements and then add those odd elements repeatedly into the same list. Which means if odd number is present twice in a list then after processing the odd number will be present four times in that same list.

For this requirement we will have many approaches where we use the for loop and the in condition or we take help of of itertools module. We also check for the odd condition by dividing each element with two.

Example

 Live Demo

from itertools import chain
import numpy as np

data_1 = [2,11,5,24,5]
data_2=[-1,-2,-9,-12]
data_3= [27/3,49/7,25/5]
odd_repeat_element_3=[]

# using for and in
odd_repeat_element = [values for i in data_1 for values in (i, )*(i % 2 + 1)]

print("Given input values:'", data_1)
print("List with odd number repeated values:", odd_repeat_element)

# Using chain from itertools
odd_repeat_element_2 = list(chain.from_iterable([n]
if n % 2 == 0 else [n]*2 for n in data_2))

print("\nGiven input values:'", data_2)
print("List with odd number repeated values:", odd_repeat_element_2)

# Using extend from mumpy
for m in data_3:
   (odd_repeat_element_3.extend(np.repeat(m, 2, axis = 0))
if m % 2 == 1 else odd_repeat_element_3.append(m))

print("\nGiven input values:'", data_3)
print("List with odd number repeated values:", odd_repeat_element_3)

Running the above code gives us the following result:

Given input values:' [2, 11, 5, 24, 5]
List with odd number repeated values: [2, 11, 11, 5, 5, 24, 5, 5]

Given input values:' [-1, -2, -9, -12]
List with odd number repeated values: [-1, -1, -2, -9, -9, -12]

Given input values:' [9.0, 7.0, 5.0]
List with odd number repeated values: [9.0, 9.0, 7.0, 7.0, 5.0, 5.0]
raja
Published on 02-Jan-2020 14:15:11
Advertisements