Open In App

Python | Element repetition in list

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes we require to add a duplicate value in the list for several different utilities. This type of application is sometimes required in day-day programming. Let’s discuss certain ways in which we add a clone of a number to its next position. 

Method #1: Using list comprehension 

In this method, we just iterate the loop twice for each value and add it to the desired new list. This is just a shorthand alternative to the naive method. 

Python3




# Python3 code to demonstrate
# to perform element duplication
# using list comprehension
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension
# to perform element duplication
res = [i for i in test_list for x in (0, 1)]
 
# printing 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]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), since we are creating a new list with the duplicated elements.

Method #2 : Using reduce() + add We can also use the reduce function to act the function to perform the addition of a pair of similar numbers simultaneously in the list. 

Python3




# Python3 code to demonstrate
# to perform element duplication
# using reduce() + add
from operator import add
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using reduce() + add
# to perform element duplication
res = list(reduce(add, [(i, i) for i in test_list]))
 
# printing 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]

Time complexity: O(n).
Auxiliary space: O(n).

Method #3: Using itertools.chain().from_iterable() from_iterable function can also be used to perform this task of adding a duplicate. It just makes the pair of each iterated element and inserts it successively. 

Approach:

  1. Initialize the original list test_list with some elements.
  2. Print the original list using print().
  3. Create a list comprehension that creates a list of duplicated elements for each element of the original list test_list.
  4. Use itertools.chain.from_iterable() function to flatten the list of duplicated elements into a single list.
  5. Convert the result to a list using list().
  6. Print the result using print().

Python3




# Python3 code to demonstrate
# to perform element duplication
# using itertools.chain.from_iterable()
import itertools
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using itertools.chain.from_iterable()
# to perform element duplication
res = list(itertools.chain.from_iterable([i, i] for i in test_list))
 
# printing 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]

Time complexity: O(n), where n is the length of the input list ‘test_list’.
Auxiliary space: O(n), as we are creating a new list ‘res’ of the same size as the input list ‘test_list’. The use of itertools.chain.from_iterable() function does not increase the space complexity as it creates an iterator and does not create a new list.

Method #4: Using repeat

You can use the repeat method of the itertools module to achieve the desired result of adding a duplicate element to the list. Here is how you can do it:

Python3




from itertools import repeat
 
# Initializing the list
test_list = [4, 5, 6, 3, 9]
 
# Printing the original list
print("The original list is:", test_list)
 
# Using the repeat method to add a duplicate element
res = [i for i in test_list for _ in repeat(None, 2)]
 
# Printing the result
print("The list after element duplication:", res)
# This code is contributed by Edula Vinay Kumar Reddy


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]

Time complexity: O(n)
Auxiliary Space: O(n)

Method #5:Using extend() method

Algorithm:

  1. Initialize an empty list res.
  2. Iterate through each element i in test_list.
  3. Append i to res twice using the extend() method.
  4. Return res after all elements have been processed.
  5. Print the final result.

Python3




test_list = [4, 5, 6, 3, 9]
# Printing the original list
print("The original list is:", test_list)
res = []
for i in test_list:
    res.extend([i, i])
print("The list after element duplication: " + str(res))
#This code is contributed by Vinay Pinjala.


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]

Time Complexity: O(n), where n is the number of elements in test_list. The algorithm iterates through each element in test_list exactly once.
Auxiliary Space: O(n), where n is the number of elements in test_list. The space used by res scales linearly with the size of test_list.

Method #6: Using slicing and concatenation

Approach:

  • Create a new list res using list comprehension that contains duplicate elements of the original list. 
  • For each element i in the original list test_list, create a new list that contains 2 copies of the element i.
    • Flatten the nested list of duplicate elements into a single list using another for loop and store it in the res variable.
  • Print the resulting list using the print() function.

Python3




# Initializing the list
test_list = [4, 5, 6, 3, 9]
 
# Printing the original list
print("The original list is:", test_list)
 
# Using list comprehension to add a duplicate element
res = [i for i in test_list for _ in range(2)]
 
# Printing the result
print("The list after element duplication:", 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]

Time complexity: O(n), where n is the length of the list. This is because we only need to iterate over the list once to duplicate its elements.
Auxiliary space: O(n), where n is the length of the list. This is because we are creating a new list with the same length as the original list to store the duplicated elements.

Method #7: Using numpy:

Algorithm :

  1. Initialize the input list test_list.
  2. Print the original input list.
  3. Use the np.repeat() method from NumPy to create a new array with duplicated elements.
  4. Assign the result to the res variable.
  5. Print the resulting list.

Python3




import numpy as np
 
# initializing list
test_list = [4, 5, 6, 3, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using NumPy to perform element duplication
res = np.repeat(test_list, 2)
 
# printing result
print("The list after element duplication " + str(res))
# This code is contributed by Rayudu.


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]

Time complexity: O(N)

The time complexity of the np.repeat() method is O(n) where n is the number of elements in the input list.
The print statements take constant time, so they don’t affect the overall time complexity.
Therefore, the time complexity of the code is O(n).

Auxiliary Space: O(N)

The space complexity of the code is O(n) because the res variable stores a new array with duplicate elements, which requires n*2 units of space.
The space complexity of the input list is also O(n).
Therefore, the total space complexity of the code is O(n).

Method #8: Using heapq module:

Algorithm :

  1. Import the heapq module and initialize the test_list
  2. Print the original test_list
  3. Use the heapq.merge() method to merge the test_list with itself
  4. Convert the result to a list using list()
  5. Print the final result

Python3




# Python program for the above approach
import heapq
 
# Initializing the list
test_list = [4, 5, 6, 3, 9]
 
# Printing the original list
print("The original list is:", test_list)
 
# Using heapq method to add a duplicate element
res = heapq.merge(test_list, test_list)
 
# Converting the result to a list
res = list(res)
 
# Printing the result
print("The list after element duplication:", res)


Output

The original list is: [4, 5, 6, 3, 9]
The list after element duplication: [4, 4, 5, 5, 6, 3, 6, 3, 9, 9]

Time complexity:
The time complexity of the code is O(n log n), where n is the length of the test_list. This is because the heapq.merge() method has a time complexity of O(n log n), and the list() method has a time complexity of O(n).

Space complexity:
The space complexity of the code is O(n), where n is the length of the test_list. This is because the heapq.merge() method returns an iterator, which does not create a new list in memory. Therefore, the space required is only for the new list created by the list() method.



Previous Article
Next Article

Similar Reads

Python - Custom element repetition
Given list of elements and required occurrence list, perform repetition of elements. Input : test_list1 = ["Gfg", "Best"], test_list2 = [4, 5] Output : ['Gfg', 'Gfg', 'Gfg', 'Gfg', 'Best', 'Best', 'Best', 'Best', 'Best'] Explanation : Elements repeated by their occurrence number. Input : test_list1 = ["Gfg"], test_list2 = [5] Output : ['Gfg', 'Gfg'
6 min read
Python - Incremental and Cyclic Repetition of List Elements
Sometimes, while working with Python lists, we can have a problem in which we need to repeat elements K times. But we can have variations in this and have to repeat elements in cyclic and incremental way. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + enumerate() This is brute force way in which this task c
4 min read
Python - String Repetition and spacing in List
Sometimes while working with Python, we can have a problem in which we need to perform the repetition of each string in list and also attach a deliminator to each occurrence. This kind of problem can occur in day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This task can be performed in brut
7 min read
Randomly select elements from list without repetition in Python
Python's built-in module in random module is used to work with random data. The random module provides various methods to select elements randomly from a list, tuple, set, string or a dictionary without any repetition. Below are some approaches which depict a random selection of elements from a list without repetition by: Method 1: Using random.sam
3 min read
Python - Index Value repetition in List
Given a list of elements, The task is to write a Python program to repeat each index value as per the value in that index. Input : test_list = [3, 0, 4, 2] Output : [0, 0, 0, 2, 2, 2, 2, 3, 3] Explanation : 0 is repeated 3 times as its index value is 3. Input : test_list = [3, 4, 2] Output : [0, 0, 0, 1, 1, 1, 1, 2, 2] Explanation : 1 is repeated 4
7 min read
Python - Consecutive Repetition of Characters
Sometimes, while working with character lists we can have a problem in which we need to perform consecutive repetition of characters. This can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is one of the way in which this task can be performed. In this, we
5 min read
Python - Custom Consecutive character repetition in String
Given a String, repeat characters consecutively by number mapped in dictionary. Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 3} Output : GGGeekkkkksss444GGGeekkkkksss Explanation : Each letter repeated as per value in dictionary.Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k"
4 min read
Python - Character repetition string combinations
Given a string list and list of numbers, the task is to write a Python program to generate all possible strings by repeating each character of each string by each number in the list. Input : test_list = ["gfg", "is", "best"], rep_list = [3, 5, 2]Output : ['gggfffggg', 'iiisss', 'bbbeeesssttt', 'gggggfffffggggg', 'iiiiisssss', 'bbbbbeeeeesssssttttt'
3 min read
Python | Slicing list from Kth element to last element
Python list slicing slices the list from start index till end - 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let's discuss ways in which last element can be included during a list slice. Method #1 : Using None During list slicing, giving the d
6 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
Practice Tags :