- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Append Odd element twice in Python
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.
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("
Given 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("
Given 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]
- How to append element in the list using Python?
- Python – Append given number with every element of the list
- How to append an element before an element using jQuery?
- How to append an element after an element using jQuery?
- append() and extend() in Python
- append() and extend() in Python program
- Find the element that appears once in an array where every other element appears twice in C++
- Why do backslashes appear twice while printing in Python?
- Largest Number At Least Twice of Others in Python
- How to append a list to a Pandas DataFrame using append() in Python?
- Python Program to Find Element Occurring Odd Number of Times in a List
- How to append elements in Python tuple?
- Append multiple lists at once in Python
- Odd Even Linked List in Python
- Python – Append List every Nth index