Open In App

Python | Add element at alternate position in list

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python list, we can have a problem in which we need to add elements in list alternatively i.e at even positions and reorder the list accordingly. This has a potential application in many domains such as day-day programming and competitive programming. Let’s discuss certain way in which this problem can be solved. 
Method : Using join() + list() This method can be used to solve this problem in one line. In this, we just join all the elements alternatively with target element and then convert back to list using list(). 

Python3




# Python3 code to demonstrate working of
# Add element at alternate position in list
# using join() + list()
 
# initialize list
test_list = ['a', 'b', 'c', 'd', 'e', 'f']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize ele
ele = '#'
 
# Add element at alternate position in list
# using join() + list()
res = list(ele.join(test_list))
 
# printing result
print("List after alternate addition : " + str(res))


Output

The original list is : ['a', 'b', 'c', 'd', 'e', 'f']
List after alternate addition : ['a', '#', 'b', '#', 'c', '#', 'd', '#', 'e', '#', 'f']

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Using the itertools.chain() function: Use the itertools.chain() function to iterate through the list and add the target element at every even index. Time complexity of this approach would be O(n) and Auxiliary space would be O(1).

Python3




import itertools
 
# initialize list
test_list = ['a', 'b', 'c', 'd', 'e', 'f']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize ele
ele = '#'
 
# Add element at alternate position in list
# using itertools.chain()
res = list(itertools.chain.from_iterable(zip(test_list, [ele]*(len(test_list)-1))))
 
# printing result
print("List after alternate addition : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : ['a', 'b', 'c', 'd', 'e', 'f']
List after alternate addition : ['a', '#', 'b', '#', 'c', '#', 'd', '#', 'e', '#']

Time Complexity: O(n), where n is the length of test_list.
Auxiliary Space: O(n), where n is the number of elements in res list.



Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads