-4
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!

OVL02
  • 19
  • you should search existing SO answers before posting. The reason for so many downvotes is that this question has been answered multiple times! – Vivek Kalyanarangan Nov 25 '17 at 07:16
  • Porbably shouldn't use `list` as the name, that would conflict with the built-in function [`list()`](https://docs.python.org/2/library/functions.html#func-list). – RoadRunner Nov 25 '17 at 07:24

3 Answers3

2

Here you go:

for i in index:
    list[i] = letter
Trevor
  • 481
  • 10
  • 25
2

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']
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
1

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
Aisha Javed
  • 169
  • 13