Want to append Odd element twice in Python? Below is an example to append Odd element twice in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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) |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.