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
Python Program to repeat elements at custom indices
When working with lists, you might need to repeat certain elements at specific positions. This can be achieved using Python's enumerate() function along with the extend() and append() methods to create a new list with duplicated elements at custom indices.
Basic Approach Using enumerate()
The most straightforward method is to iterate through the original list and check if the current index should have its element repeated ?
original_list = [34, 56, 77, 23, 31, 29, 62, 99]
print("The original list is:")
print(original_list)
indices_to_repeat = [3, 1, 4, 6]
result = []
for index, element in enumerate(original_list):
if index in indices_to_repeat:
result.extend([element, element]) # Add element twice
else:
result.append(element) # Add element once
print("The result is:")
print(result)
The original list is: [34, 56, 77, 23, 31, 29, 62, 99] The result is: [34, 56, 56, 77, 23, 23, 31, 31, 29, 62, 62, 99]
Using List Comprehension
A more concise approach using list comprehension with conditional logic ?
original_list = [34, 56, 77, 23, 31, 29, 62, 99]
indices_to_repeat = [3, 1, 4, 6]
result = [element for i, element in enumerate(original_list)
for _ in range(2 if i in indices_to_repeat else 1)]
print("Original list:", original_list)
print("Result:", result)
Original list: [34, 56, 77, 23, 31, 29, 62, 99] Result: [34, 56, 56, 77, 23, 23, 31, 31, 29, 62, 62, 99]
Custom Repetition Count
You can also specify how many times each element should be repeated using a dictionary ?
original_list = ['A', 'B', 'C', 'D', 'E']
repeat_config = {1: 3, 3: 2} # Index 1 repeats 3 times, index 3 repeats 2 times
result = []
for index, element in enumerate(original_list):
repeat_count = repeat_config.get(index, 1) # Default to 1 repetition
result.extend([element] * repeat_count)
print("Original list:", original_list)
print("Repeat configuration:", repeat_config)
print("Result:", result)
Original list: ['A', 'B', 'C', 'D', 'E']
Repeat configuration: {1: 3, 3: 2}
Result: ['A', 'B', 'B', 'B', 'C', 'D', 'D', 'E']
How It Works
The process involves the following steps:
enumerate() provides both index and element from the original list
extend() adds multiple elements to the result list when repetition is needed
append() adds a single element when no repetition is required
The
inoperator efficiently checks if an index exists in the repetition list
Conclusion
Use enumerate() with extend() to repeat elements at specific indices. List comprehension provides a more concise solution, while dictionary-based configuration allows flexible repetition counts for different use cases.
