Home > database >  Function for replacing the element in a list in Python
Function for replacing the element in a list in Python

Time:11-14

Is there a function that replaces element in a list in python like

given_list=['_','_','_','_',]

now i want to replace the '_' with a letter. does such function exist. if not, how can i do it

CodePudding user response:

I am pretty sure there so no function for doing this with a list/array but you can use the following code (I am not good with python so my code might not be that good):

given_list = ['_','_','_']

for item in  given_list:
     if item=='_':
          given_list[given_list.index(item)] = 'a'

print(given_list)

output: ['a','a','a']

CodePudding user response:

You can do this task using for loop. Iterate the list, check for every element if it is "_". If yes, repace it with the letter. Your code:

given_list=['_','_','_','_',]
letter="some_letter"
for i in range(0,len(given_list)):
    if given_list[i]=="_":
        given_list[i]=letter
print(given_list)

Replace the "some_letter" with the actual letter you want

  • Related