
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to repeat elements at custom indices
When it is required to repeat elements at custom indices, a simple iteration, enumerate attribute, the ‘extend’ method and the ‘append’ method are used.
Below is a demonstration of the same −
Example
my_list = [34, 56, 77, 23, 31, 29, 62, 99] print("The list is :") print(my_list) index_list = [3, 1, 4, 6] my_result = [] for index, element in enumerate(my_list): if index in index_list: my_result.extend([element, element]) else : my_result.append(element) print("The result is :") print(my_result)
Output
The 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]
Explanation
A list is defined and displayed on the console.
Another list of integers is defined.
An empty list is defined.
The list is iterated over and enumerate attribute is used, and the elements of the list are compared with the integer list.
If an element is present in the integer list, it is added to the empty list in element’s index using ‘extend’ method.
Otherwise, it is added to empty list using ‘append’ method.
This is the output that is displayed on the console.
- Related Articles
- Python program to remove elements at Indices in List
- Python Group elements at same indices in a multi-list
- Program to find minimum possible difference of indices of adjacent elements in Python
- Python program to Uppercase selective indices
- Python Pandas - Repeat elements of an Index
- Pair of similar elements at different indices in JavaScript
- Python – Grouped Consecutive Range Indices of Elements
- Program to get indices of a list after deleting elements in ascending order in Python
- Program to count indices pairs for which elements sum is power of 2 in Python
- Find elements of a list by indices in Python
- Program to shuffle string with given indices in Python
- Program to find indices or local peaks in Python
- Python Program that print elements common at specified index of list elements
- Python program to sort string in custom order
- Python Program to get indices of sign change in a list

Advertisements