How to Replace Values At Specific Indexes of a Python List

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

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.

Replace string in specific index in list of lists python

Use indexing:

newlist = []
for l in mylist:
l[1] = l[1].replace("test", "my")
newlist.append(l)
print(newlist)

Or oneliner if you always have two elements in the sublist:

newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)

Output:

[['test_one', 'my_two'], ['test_one', 'my_two']]

Replace elements in lists based on indexes python

Try this:

rest=[5, 7, 11, 4]
b=[21, 22, 33, 31, 23, 15, 19, 13, 6]
last=[33, 19, 40, 21, 31, 22, 6, 15, 13, 23]

for i, l in enumerate(last):
if l in b:
if b.index(l) < len(rest):
last[i] = rest[b.index(l)]

print(last)

How to replace values in a matrix based on specific indices?

You can run e.g.:

matrix[tuple(coords.T)] = 1


Related Topics



Leave a reply



Submit