Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Element repetition in list in Python
There are scenarios when we need to repeat the values in a list. This duplication of values can be achieved in Python using several approaches. Let's explore different methods to duplicate each element in a list.
Using List Comprehension with Nested Loop
This is a straightforward approach where we use list comprehension with nested iteration to duplicate each element ?
# Given list
data = ['Mon', 'Tue', 9, 3, 3]
print("Given list:", data)
# Adding another element for each element
new_list = [i for i in data for n in (0, 1)]
# Result
print("New list after duplication:", new_list)
Given list: ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
Using itertools.chain
The itertools.chain.from_iterable() function flattens nested iterables efficiently. We create tuples of duplicated elements and chain them together ?
import itertools
# Given list
data = ['Mon', 'Tue', 9, 3, 3]
print("Given list:", data)
# Adding another element for each element
new_list = list(itertools.chain.from_iterable([n, n] for n in data))
# Result
print("New list after duplication:", new_list)
Given list: ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
Using reduce with operator.add
The reduce() function applies a function cumulatively to items in a sequence. Here we use it with operator.add to concatenate tuples of duplicated elements ?
from functools import reduce
from operator import add
# Given list
data = ['Mon', 'Tue', 9, 3, 3]
print("Given list:", data)
# Adding another element for each element
new_list = list(reduce(add, [(i, i) for i in data]))
# Result
print("New list after duplication:", new_list)
Given list: ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
Using Simple Loop
A more readable approach using a simple loop to append each element twice ?
# Given list
data = ['Mon', 'Tue', 9, 3, 3]
print("Given list:", data)
# Create new list with duplicated elements
new_list = []
for item in data:
new_list.extend([item, item])
# Result
print("New list after duplication:", new_list)
Given list: ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| List Comprehension | Good | Fast | Efficient |
| itertools.chain | Medium | Very Fast | Very Efficient |
| reduce | Low | Slower | Less Efficient |
| Simple Loop | Very Good | Medium | Good |
Conclusion
For duplicating list elements, use list comprehension for simplicity or itertools.chain for better performance. The simple loop approach offers the best readability for beginners.
