Open In App

Python – Replace index elements with elements in Other List

Last Updated : 05 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python data, we can have a problem in which we have two lists and we need to replace positions in one list with the actual elements from other list. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension This is one way to solve this problem. In this we just iterate through the list and assign the index value from one list to other. 

Python3




# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
             
# printing result
print ("The lists after index elements replacements is : " + str(res))


Output : 

The original list 1 is : [‘Gfg’, ‘is’, ‘best’] The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0] The lists after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’, ‘Gfg’]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.

  Method #2 : Using map() + lambda The combination of above functions can be used to perform this task. In this, we perform task of extension of logic to every element using map() and lambda functions. 

Python3




# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using map() + lambda
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Replace index elements with elements in Other List
# using map() + lambda
res = list(map(lambda idx: test_list1[idx], test_list2))
             
# printing result
print ("The lists after index elements replacements is : " + str(res))


Output : 

The original list 1 is : [‘Gfg’, ‘is’, ‘best’] The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0] The lists after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’, ‘Gfg’]

Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.

# Method #3 : Using numpy.take()
We can also perform this task by using numpy module. In this, we just have to pass the both list to numpy.take() and then assign the result to list.

Python3




# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using numpy.take()
   
# import numpy
import numpy as np
   
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
   
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
   
# Replace index elements with elements in Other List
# using numpy.take()
res = np.take(test_list1, test_list2)
               
# printing result
print ("The lists after index elements replacements is : " + str(res))


Output :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’, ‘Gfg’]

Time complexity: O(n)

Auxiliary Space: O(n)

Method #4: using a for loop and a dictionary

Python3




# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Create a dictionary to map indices to elements in test_list1
index_map = {index: element for index, element in enumerate(test_list1)}
 
# Replace index elements with elements in Other List using a for loop
res = [index_map[idx] for idx in test_list2]
             
# printing result
print ("The lists after index elements replacements is : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list 1 is : ['Gfg', 'is', 'best']
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is', 'best', 'Gfg']

Time complexity: O(n)

Auxiliary Space: O(n)

Method #5: Using pandas library

step-by-step algorithm for implementing the approach

  1. Import the pandas module.
  2. Define the two original lists.
  3. Create a DataFrame object with one column containing the values from the first list.
  4. Use the loc[] function of the DataFrame to extract the values from the first list corresponding to the indices in the second list.
  5. Convert the resulting series object to a list.
  6. Assign the resulting list to a new variable.
  7. Print the resulting list.

Python3




import pandas as pd
 
# Initializing the two lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
 
# Creating a dataframe with one column ('a') containing the values from test_list1
df = pd.DataFrame({'a': test_list1})
 
# Extracting the values from test_list1 corresponding to the indices in test_list2
# by using the loc[] function of the dataframe and converting the result to a list
res = df.loc[test_list2, 'a'].tolist()
 
# Printing the resulting list
print("The lists after index elements replacements is : " + str(res))


output

The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is', 'best', 'Gfg']

Time complexity: O(n) 

Space complexity: O(n) 

Method #5 : Using zip() function

Use the zip() function to combine test_list1 and test_list2 element-wise.
Loop through the resulting tuples obtained in step 1.
Append the corresponding element from test_list1 to a new list res.
Print the final result list res.

Python3




# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Using zip() function
res = [test_list1[i] for i in test_list2]
 
# printing result
print ("The lists after index elements replacements is : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list 1 is : ['Gfg', 'is', 'best']
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is', 'best', 'Gfg']

Time complexity: O(n), where n is the length of test_list2.
Auxiliary space: O(n), where n is the length of test_list2.



Similar Reads

Python | Replace elements in second list with index of same element in first list
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Method #1: Using Iteration C/C++ Code # Python code to replace every element # in second list with index of first element. # List Initialization Input1 = ['cut', 'god', 'pass']
5 min read
Python | Replace sublist with other in list
Sometimes, while working with Python, we can have a problem in which we need to manipulate a list in such a way that we need to replace a sublist with another. This kind of problem is common in the web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop ( When sublist is given ) This method is
10 min read
Python program to remove duplicate elements index from other list
Given two lists, the task is to write a Python program to remove all the index elements from 2nd list which are duplicate element indices from 1st list. Examples: Input : test_list1 = [3, 5, 6, 5, 3, 7, 8, 6], test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] Output : [1, 7, 6, 9, 10] Explanation : 3, 7 and 11 correspond to 2nd occurrence of 5, 3 and 6, henc
7 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" This problem has existing solution please refer Replace all occurrences of string AB with C without using ex
1 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python - Retain K match index values from other list
Sometimes, while working with Python lists, we can have a problem in which we need to retain only the strings with match a particular value from the corresponding list at same index. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() The combination
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Combine list with other list elements
Given two lists, combine list with each element of the other list. Examples: Input : test_list = [3, 5, 7], pair_list = ['Gfg', 'is', 'best'] Output : [([3, 5, 7], 'Gfg'), ([3, 5, 7], 'is'), ([3, 5, 7], 'best')] Explanation : All lists paired with each element from other list. Input : test_list = [3, 5, 7], pair_list = ['Gfg', 'best'] Output : [([3
6 min read
Python - Test if elements of list are in Min/Max range from other list
Given two lists, the task is to write a Python Program to return true if all elements from second list are in range of min and max values of the first list. Examples: Input : test_list = [5, 6, 3, 7, 8, 10, 9], range_list = [4, 7, 9, 6] Output : True Explanation : Min and max in list 1 are 3 and 10, all elements are in range in other list. Input :
6 min read
Practice Tags :