Python | Append Odd element twice
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) |
chevron_right
filter_none
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) |
chevron_right
filter_none
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) |
chevron_right
filter_none
Output:
Initial list is:' [1, 2, 3, 8, 9, 11] New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]
Recommended Posts:
- append() and extend() in Python
- numpy.append() in Python
- Python | Append multiple lists at once
- Python| Pandas dataframe.append()
- Python | Pandas TimedeltaIndex.append()
- Python | Pandas Series.append()
- Python | Pandas Index.append()
- Python | Append at front and remove from rear
- Python | Perform append at beginning of list
- Python | Append suffix/prefix to strings in list
- Python | Slicing list from Kth element to last element
- Python | Three element sum in list
- Python | How to get the last element of list
- Python | Get last element of each sublist
- Python | Indices of Kth element value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



