Method # 1: Using List Comprehension
In this method, we simply loop twice for each value and add to the new list. This is just a concise alternative to the naive method.
# Python3 demo code # duplicate the element # using comprehension list # initializing list test_list = [ 4 , 5 , 6 , 3 , 9 ] # print original list pri nt ( "The original list is:" + str (test_list)) # using comprehension list # duplicate element res = [i for i in test_list for x in ( 0 , 1 )] # print result print ( "The list after element duplication" + str (res)) |
Output:
The original list is: [4, 5, 6, 3, 9] The list after element duplication [4, 4, 5 , 5, 6, 6, 3, 3, 9, 9]
Method # 2: Using redu () + add
We can also use the Reduce function to use a function to simultaneously add a pair of similar numbers to the list.
# Python3 demo code # duplicate the element # using Reduce () + add from operator import add # initializing list test_list = [ 4 , 5 , 6 , 3 , 9 ] # print original list print ( "The original list is:" + str (test_list)) # using Reduce () + add code> # duplicate the element res = list ( reduce (add, [(i, i) for i in test_list])) # print result print ( "The list after element duplication" + str (res)) |
Output:
The original list is: [4, 5, 6, 3, 9] The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
Method # 3: Using i tertools.chain (). from_iterable ()
The from_iterable function can also be used to accomplish this task of adding a duplicate. It just creates a pair of each repeating element and inserts it sequentially.
# Python3 demo code # duplicate the element # use itertools.chain.from_iterable () import itertools # initialization list test_list = [ 4 , 5 , 6 , 3 , 9 ] # print original list print ( "The original list is:" + str (test_list)) # using itertools.chain.from_iterable () # duplicate element res = list (itertools.chain.from_iterable ([i, i] for i in test_list)) # print result print (< / code> "The list after element duplication" + str (res)) |
Output:
The original list is: [4, 5, 6, 3, 9] The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
Python | Repeating an item in a list Python functions: Questions
Python | Repeating an item in a list repeat: Questions