VOOZH about

URL: https://www.geeksforgeeks.org/python/python-append-odd-element-twice/

⇱ Python | Append Odd element twice - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Append Odd element twice

Last Updated : 15 Mar, 2023

Given a list of numbers, 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 


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

Time Complexity: O(n), Here n is the size of the list.
Auxiliary Space: O(n)

Method #2: Using itertools 


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

Time Complexity: O(n), Here n is the size of the list.
Auxiliary Space: O(n)

Method #3: Using Numpy array 

Output:

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

Time Complexity: O(n), Here n is the size of the list.
Auxiliary Space: O(n)

Method #4 : Using extend() method


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

Time Complexity : O(N)
Auxiliary Space : O(N)

Method#5: Using Recursive method.

The algorithm creates a new list from the input list with the condition to append every odd element twice, using a recursive function.

  1. Define a function append_odd_twice that takes an input list as its argument.
  2. If the input list is empty, return an empty list (base case).
  3. Otherwise, if the first element of the input list is odd, append it twice to the output list, otherwise append it once.
  4. Recursively call the function with the rest of the input list and append the result to the output list.
  5. Return the output list.

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

The time complexity of the algorithm is O(n), where n is the length of the input list. The recursive function performs a constant amount of work for each element in the list. 

The space complexity of the algorithm is also O(n), since the recursive function creates a new list for each recursive call.

Comment
Article Tags: