Write a Python Program to Replace index elements with elements in Other List


The program is a python script that replaces the elements of a list with elements from another list based on the index value of the second list.

Here's what the program does in detail:

  • Two lists "a" and "b" are defined. "a" is a list of strings and "b" is a list of integers.
  • The original lists "a" and "b" are printed using the "print()" function.
  • A list comprehension is used to create a new list "res" that contains the elements from "a" that correspond to the index values in "b".
  • The list comprehension uses "i" as the index for "a" and takes the values of "i" from the list "b". So, for each value of "i" in "b", the element of "a" at the index "i" is added to "res".
  • The final list "res" is printed after the elements are replaced.

Source Code

a = ['Tutor Joes', 'Computer', 'Education']
b = [2 ,1 ,0 ,1 ,0 ,2 ,2 ,0 ,1 ,0 ,1 ,2]
print("List 1 : " , a)
print("List 2 : " , b)
res = [a[i] for i in b]
 
print ("After Index Elements Replacements is : " ,res)

Output

List 1 :  ['Tutor Joes', 'Computer', 'Education']
List 2 :  [2, 1, 0, 1, 0, 2, 2, 0, 1, 0, 1, 2]

After Index Elements Replacements is :  ['Education', 'Computer', 'Tutor Joes', 'Computer', 'Tutor Joes', 'Education', 'Education', 'Tutor Joes', 'Computer', 'Tutor Joes', 'Computer', 'Education']



Example Programs