Python - Index Value repetition in List
Last Updated :
08 May, 2023
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 times as its value is 4.
Method #1: Using list comprehension + enumerate()
In this, we perform task of repetition using * operator, and enumerate() is used to get indices along with values for repetition. List comprehension is used to iteration all the elements.
Python3
# Python3 code to demonstrate working of
# Index Value repetition in List
# Using list comprehension + enumerate()
# initializing Matrix
test_list = [3, 0, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# enumerate() gets index and value of similar index element
res = [ele for sub in ([idx] * ele for idx,
ele in enumerate(test_list)) for ele in sub]
# printing result
print("Constructed List : " + str(res))
OutputThe original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2: Using chain.from_iterable() + list comprehension
In this, we perform the last step of flattening of list using chain.from_iterable(). List comprehension performs the task of iteration of all the elements.
Python3
# Python3 code to demonstrate working of
# Index Value repetition in List
# Using chain.from_iterable() + list comprehension
import itertools
# initializing Matrix
test_list = [3, 0, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# enumerate() gets index and
# value of similar index element
# from_iterable() used to flatten
res = list(itertools.chain(*([idx] * ele for idx,
ele in enumerate(test_list))))
# Printing result
print("Constructed List : " + str(res))
OutputThe original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as we are creating a new list of length n to store the result.
Method #3: Using extend() method
In this, we perform task of repetition using * operator, and add the elements using the extend() method in the new list.
Python3
# Python3 code to demonstrate working of
# Index Value repetition in List
# initializing Matrix
test_list = [3, 0, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in range(0, len(test_list)):
res.extend([i]*test_list[i])
# printing result
print("Constructed List : " + str(res))
OutputThe original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time Complexity: O(n*m)
Auxiliary Space: O(k)
Method #4: Using numpy.repeat() and numpy.arange():
Algorithm :
1. Initialize the input list test_list.
2. Import the numpy module as np.
3.Use np.arange() to create an array of integers from 0 to len(test_list)-1, representing the indices of test_list.
4. Use np.repeat() to repeat each index of the array a certain number of times based on the corresponding value in test_list.
5.Convert the output of np.repeat() to a list using tolist().
6. Print the resulting list.
Python3
# Importing the numpy module as np
import numpy as np
# Initializing the input list
test_list = [3, 0, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# Using numpy's repeat() function to repeat each index of the input list
# the number of times specified by the value at that index
# The arange() function is used to create an array of integers from 0 to len(test_list)-1
# The output of repeat() is then converted to a list using tolist()
res = np.repeat(np.arange(len(test_list)), test_list).tolist()
# Printing the constructed list
print("Constructed List : " + str(res))
#This code is contributed by Jyothi pinjala.
Output:
The original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time complexity: O(n*m), where n is the length of the input list test_list, and m is the maximum value in test_list. This is because the repeat() function needs to iterate through each element of the input list and repeat each index a certain number of times based on the value at that index. The arange() function also needs to create an array of integers from 0 to len(test_list)-1.
Auxiliary space: O(n*m), because the output list res can contain up to n*m elements, which is the total number of index-value pairs in the output list. However, in practice, the number of repeated elements in the output list will likely be much smaller than n*m, depending on the values in test_list.
Method 5 :using the built-in function map() and lambda function.
Step-by-step approach:
- Initialize the input list test_list.
- Use the map() function to apply a lambda function to each element of the input list. The lambda function takes two arguments: the index i and the value v of each element in the input list. The lambda function returns a list of i repeated v times for each element
- Flatten the resulting list of lists using the built-in function sum().
- Print the original and constructed list.
Below is the implementation of the above approach:
Python3
test_list = [3, 0, 4, 2]
res = list(map(lambda i, v: [i] * v, range(len(test_list)), test_list))
res = sum(res, [])
print("The original list is : " + str(test_list))
print("Constructed List : " + str(res))
test_list = [3, 0, 4, 2]
res = list(map(lambda i, v: [i] * v, range(len(test_list)), test_list))
res = sum(res, [])
print("The original list is : " + str(test_list))
print("Constructed List : " + str(res))
OutputThe original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
The original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Method #6 : Using append() method + nested for loop
Approach
- Initiate a nested for loop to append each element of test_list to output list by index times
- Display output list
Python3
# Python3 code to demonstrate working of
# Index Value repetition in List
# initializing Matrix
test_list = [3, 0, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in range(0, len(test_list)):
for j in range(test_list[i]):
res.append(i)
# printing result
print("Constructed List : " + str(res))
OutputThe original list is : [3, 0, 4, 2]
Constructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time Complexity : O(N*N) ,N - length of test_list
Auxiliary Space: O(N) ,N - length of output list
Method 7 : Using itertools and repeat()
Steps:
- Import the itertools module.
- Create the input list, test_list.
- Use the chain.from_iterable() function from itertools to flatten the result of the repeat() function.
- Use the repeat() function from itertools with a nested for loop to create a list of repeated index values based on the input list.
- Convert the resulting iterable to a list and assign it to the variable res.
- Print the constructed list.
Python3
import itertools
test_list = [3, 0, 4, 2]
res = list(itertools.chain.from_iterable(itertools.repeat(idx, ele) for idx, ele in enumerate(test_list)))
print("Constructed List : " + str(res))
OutputConstructed List : [0, 0, 0, 2, 2, 2, 2, 3, 3]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Similar Reads
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
String Repetition and spacing in List - Python
We are given a list of strings and our task is to modify it by repeating or adding spaces between elements based on specific conditions. For example, given the list `a = ['hello', 'world', 'python']`, if we repeat each string twice, the output will be `['hellohello', 'worldworld', 'pythonpython']. U
2 min read
Python - Values Frequency Index List
Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
4 min read
Python - Ways to find indices of value in list
In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python | Index minimum value Record
In Python, we can bind structural information in the form of tuples and then can retrieve the same, and has manyfold applications. But sometimes we require the information of a tuple corresponding to a minimum value of another tuple index. This functionality has many applications such as ranking. Le
4 min read
Accessing index and value in Python list
We are given a list, and our task is to access both the index and value of each element in the list using Python. For example, using enumerate(list) in a loop like for index, value in enumerate(list) allows us to access both the index and the value together.Using enumerate() enumerate() is preferred
2 min read
Python | Assign value to unique number in list
We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id's. Let's discuss certain ways in which this problem can be solved. Method #1: Using enumerate() + list
7 min read
Python - Convert List to Index and Value dictionary
Given a List, convert it to dictionary, with separate keys for index and values. Input : test_list = [3, 5, 7, 8, 2, 4, 9], idx, val = "1", "2" Output : {'1': [0, 1, 2, 3, 4, 5, 6], '2': [3, 5, 7, 8, 2, 4, 9]} Explanation : Index and values mapped at similar index in diff. keys., as "1" and "2". Inp
4 min read
Python - Records with Value at K index
Sometimes, while working with records, we might have a problem in which we need to find all the tuples of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Letâs discuss c
8 min read
Assign Ids to Each Unique Value in a List - Python
The task of assigning unique IDs to each value in a list involves iterating over the elements and assigning a unique identifier to each distinct value. Since lists in Python are mutable, the goal is to efficiently assign an ID to each unique element while ensuring that repeated elements receive the
3 min read