list = ['_ ','_ ','_ ','_ ','_ ']
index = [1,4]
letter = 'm'
So is there any away to change lists 1 and 4 to be 'm' using index and letter?
Thanks for help!
list = ['_ ','_ ','_ ','_ ','_ ']
index = [1,4]
letter = 'm'
So is there any away to change lists 1 and 4 to be 'm' using index and letter?
Thanks for help!
Here you go:
for i in index:
list[i] = letter
Many solutions trying same old approach here using
loop
:
Here is different approach:
Without any loop:
list_1 = ['_ ','_ ','_ ','_ ','_']
index = [1,4]
letter = 'm'
list(map(lambda x:(list_1.__setitem__(x,letter)),index))
print(list_1)
output:
['_ ', 'm', '_ ', '_ ', 'm']
Some cookies:
import operator
list(map(lambda x:operator.setitem(list_1, x, letter),index))
print(list_1)
output:
['_ ', 'm', '_ ', '_ ', 'm']
Yes, what you are trying to achieve is known as fancy indexing - using a list of indexes. But, this is possible for Numpy arrays, not in the case f simple python lists. So, a possible solution cold be:
import numpy as np
mylist = ['_ ','_ ','_ ','_ ','_ ']
index = [1,4]
letter = 'm'
list_changed=np.array(mylist)
list_changed[index]=letter
print list_changed