Python | Add element at alternate position in list

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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.