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?
EDITlist1
contains float valueslist2
contains float valuesindices
contain integers between 0
and len(list1)
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.
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.
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.
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 .
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With