Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python one liner to substitute a list indices

Tags:

python

I want to replace those elements of list1 whose indices are stored in list indices by list2 elements. Following is the current code:

j=0
for idx in indices:
   list1[idx] = list2[j]
   j+=1

Is it possible to write a one-liner for the above four lines using lambda function or list comprehension?

EDIT
list1 contains float values
list2 contains float values
indices contain integers between 0 and len(list1)

like image 700
vyi Avatar asked May 16 '16 15:05

vyi


People also ask

How do you replace a list value in Python?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

How do you replace a list in a list Python?

The easiest way to replace an item in a list is to use the Python indexing syntax . Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.

How do you replace multiple elements in a list in Python?

One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.

How do you replace an element in a specific index in a list?

You use simple indexing using the square bracket notation lst[i] = x to replace the element at index i in list lst with the new element x .


2 Answers

Use conditional expressions,

# A test case
list1 = [0, 1, 2, 3, 4, 5, 6]
list2 = ['c', 'e', 'a']
indices = [2, 4, 0]

# Use conditional expressions
new_list = [list2[indices.index(idx)] if idx in indices else v for idx, v in enumerate(list1)] # idx2 = indices.index(idx), for list2

print(new_list)
# Output
['a', 1, 'c', 3, 'e', 5, 6]
like image 194
SparkAndShine Avatar answered Sep 28 '22 07:09

SparkAndShine


Although it is not a one liner, here is an alternative that I think is more readable:

for i, v in zip(indices, list2):
    list1[i] = v
like image 44
malbarbo Avatar answered Sep 28 '22 08:09

malbarbo