The Wayback Machine - https://web.archive.org/web/20241013185212/https://www.geeksforgeeks.org/python-element-repetition-in-list/
Open In App

Python | Element repetition in list

Last Updated : 12 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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 | 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
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Count the elements in a list until an element is a Tuple
In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered. Examples: Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] Output : 4 Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4] Output : 1 Method #1: In this program we will use the concept of isinstance() to verify w
2 min read
Python | Sort a list according to the second element in sublist
In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, the second by using the sort() method, and last but not the least by the use of the sorted() meth
9 min read
Ways to remove particular List element in Python
List is an important container and is used almost in every code of day-day programming as well as web development. The more it is used, more is the required to master it and hence knowledge of its operations is necessary. Let's see the different ways of removing particular list elements. Method #1 : Using remove() remove() can perform the task of r
6 min read
Python | How to get the last element of list
Getting the last element of the list is tricky while tracking each element, here we will discuss multiple methods to get the last element of the list. So we have given a list n, Our task is to get the last element of the list using Python. Example: Input: [1, 2, 3, 4, 5, 5]Output: 5Input: ["Hello", "World"]Output: World Explanation: In both of the
6 min read
Python | Element with largest frequency in list
This is one of the most essential operation that programmer quite often comes in terms with. Be it development or competitive programming, this utility is quite essential to master as it helps to perform many tasks that involve this task to be its subtask. Lets discuss various approaches to achieve this operation. Method #1 : Naive method As the br
7 min read
Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Python | Generate successive element difference list
While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive difference in the list. Method #1 : Using list comprehension
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Preceding element tuples in list
Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the preceding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let's discuss a way in which this task can be performed. Method #1: Using for loop C/C++ Code # Python3 c
5 min read
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. Metho
2 min read
Python | Group strings at particular element in list
Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let's discuss certain way in which this problem can be performed. Method 1: Using groupby() + list comprehension + l
7 min read
Python | Find frequency of largest element in list
Given a list, the task is to find the number of occurrences of the largest element of the list.Examples: Input : [1, 2, 8, 5, 8, 7, 8] Output :3 Input : [2, 9, 1, 3, 4, 5] Output :1 Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the
2 min read
Python - Ways to print longest consecutive list without considering duplicates element
Given, a list of Numbers, the task is to print the longest consecutive (Strictly) list, without considering duplicate elements. If there is more than one answer, print anyone. These type of problem are quite common while working on some web development projects in Django or flask. Below are some ways to solve the above task. Note : If there are mul
4 min read
Python - Find first element by second in tuple List
Sometimes, while working with Python records, we can have a problem in which we need to find the first element of tuple from the given second element. This kind of problem can occur in domains such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [(4, 5), (5, 6), (1, 3), (6, 6)] K = 6 Output :
4 min read
Choose element(s) from List with different probability in Python
Have you ever wondered how to select random elements from a list with different probability in Python? In this article, we will discuss how to do the same. Let's first consider the below example. C/C++ Code import random sam_Lst = [10, 20, 3, 4, 100] ran = random.choice(sam_Lst) print(ran) In the above example, the probability of getting any elemen
4 min read
Apply function to each element of a list - Python
In this article, we will learn how to apply a function to each element of a Python list. Let's see what exactly is Applying a function to each element of a list means: Suppose we have a list of integers and a function that doubles each integer in this list. On applying the function to the list, the function should double all the integers in the lis
2 min read
Remove Last Element from List in Python
Given a list, the task is to write a Python program to remove the last element present in the list and update the original list in Python. Example: Input: ["geeks", "for", "geeks"]Output:["geeks", "for"] Input: [1, 2, 3, 4, 5]Output:[1, 2, 3, 4] Explanation: Here simply we have to remove the last element present in the list and print the resultant
4 min read
Remove all the occurrences of an element from a list in Python
The task is to perform the operation of removing all the occurrences of a given item/element present in a list. Example Input1: 1 1 2 3 4 5 1 2 1 Output1: 2 3 4 5 2 Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1. After removing the item, the output list is [2, 3, 4, 5, 2]Remove all Occurrences of an Item fr
4 min read
Python | Print list after removing element at given index
In this article, we will see how we can remove elements at a given index and print the list afterward. Example Input1: list = [10, 20, 30, 40, 50] index = 2 Output1: [10, 20, 40, 50] Input2: list = [10, 20, 40, 50] index = 0 Output2: [20, 40, 50] Print list after removing element at given indexBelow are the methods by which we can remove element at
3 min read
Python | Maximum and minimum element's position in a list
Given a list of N integers, find the maximum and minimum element's position in the Python list. Example Input: 3, 4, 1, 3, 4, 5Output: The maximum is at position 6 The minimum is at position 3Maximum and Minimum Element Position in a ListBelow are the methods and ways by which we can find minimum and maximum element position in a Python List: Using
3 min read
Check if element exists in list in Python
The list is an important container in Python as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses the Fastest way to check if a value exists in a list or not using Python. Example Input: test_list = [1, 6, 3, 5, 3, 4] 3 # Check if 3 exist or no
10 min read
Python | Count occurrences of an element in a list
Given a list in Python and a number x, count the number of occurrences of x in the given list. Examples: Input: lst = [15, 6, 7, 10, 12, 20, 10, 28, 10], x = 10Output: 3 Explanation: 10 appears three times in given list.Input: lst = [8, 6, 8, 10, 8, 20, 10, 8, 8], x = 16Output: 0Explanation: 16 appears zero times in given list.Count Occurrences of
6 min read
Python - Remove first element of list
The queue data structure is a very well-known data structure, lists in Python usually append the elements to the end of the Python list. For implementing a queue data structure, it is essential to be able to remove the front element from a list. Let's discuss the ways of removing the first element of the list. Method 1: Remove Elements From Lists i
7 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Practice Tags :