If I have a list:
characters = ['_', '_', '_', '_', '_']
and a string value
letter = a
and another list
positions = [2, 3]
How can I define a function that would replace the values of the list characters
at the positions defined by positions
with letter
so that the output would be ['_', '_', 'a', 'a', '_']
?
CodePudding user response:
You can simply use a for loop :
characters = ['_', '_', '_', '_', '_']
positions = [2, 3]
letter = "a"
for position in positions:
characters[position] = letter
print(characters)
# ['_', '_', 'a', 'a', '_']
CodePudding user response:
You can do it using a for loop. Iterate the positions
list. Now, every iteration will represent the individual position. Replace the letter to the characters
list. Your code:
def function():
characters=["_","_","_","_","_"]
letter="a"
positions=[2,3]
for i in positions: #i values will be 2 and 3. Replace the letter a at position 2 and 3
characters[i]=letter
return characters
print(function())