Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace values at specific indexes of a python list?

If I have a list:

to_modify = [5,4,3,2,1,0] 

And then declare two other lists:

indexes = [0,1,3,5] replacements = [0,0,0,0] 

How can I take to_modify's elements as index to indexes, then set corresponding elements in to_modify to replacements, i.e. after running, indexes should be [0,0,3,0,1,0].

Apparently, I can do this through a for loop:

for ind in to_modify:     indexes[to_modify[ind]] = replacements[ind] 

But is there other way to do this? Could I use operator.itemgetter somehow?

like image 853
Alcott Avatar asked Aug 29 '11 14:08

Alcott


People also ask

How do you change a value in a list at index 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 multiple values in a list Python?

Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.


2 Answers

The biggest problem with your code is that it's unreadable. Python code rule number one, if it's not readable, no one's gonna look at it for long enough to get any useful information out of it. Always use descriptive variable names. Almost didn't catch the bug in your code, let's see it again with good names, slow-motion replay style:

to_modify = [5,4,3,2,1,0] indexes = [0,1,3,5] replacements = [0,0,0,0]  for index in indexes:     to_modify[indexes[index]] = replacements[index]     # to_modify[indexes[index]]     # indexes[index]     # Yo dawg, I heard you liked indexes, so I put an index inside your indexes     # so you can go out of bounds while you go out of bounds. 

As is obvious when you use descriptive variable names, you're indexing the list of indexes with values from itself, which doesn't make sense in this case.

Also when iterating through 2 lists in parallel I like to use the zip function (or izip if you're worried about memory consumption, but I'm not one of those iteration purists). So try this instead.

for (index, replacement) in zip(indexes, replacements):     to_modify[index] = replacement 

If your problem is only working with lists of numbers then I'd say that @steabert has the answer you were looking for with that numpy stuff. However you can't use sequences or other variable-sized data types as elements of numpy arrays, so if your variable to_modify has anything like that in it, you're probably best off doing it with a for loop.

like image 117
machine yearning Avatar answered Oct 04 '22 16:10

machine yearning


numpy has arrays that allow you to use other lists/arrays as indices:

import numpy S=numpy.array(s) S[a]=m 
like image 22
steabert Avatar answered Oct 04 '22 16:10

steabert