Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replacing item in list

Hi my question relates to a post a long time ago by some user here:

Find and replace string values in Python list

For my specific situation. I have a list like this:

appl =  ['1', 'a', 'a', '2', 'a']

I want to replace only the "a single unknown" instance of "a" with just an empty space(that holds the position of where "a" used to be). I am unsure of how to do it for only one character. Can anyone help? Thanks in advance.

EDIT: i Should mention that I need to use an "index" function to first locate the "a" since it is a changing variable. And then I need code that will replace the character.

EDIT2: A lot of people are assuming the index will be 2, but I want to point out that the index of the character is not known. Also "a" will be present in the list approximately ~20 times(will remain a fixed number) but their locations will be changing. I want to replace an "a" based on user input. This is the actual list I am working with:

track  [2] =   ["|","@","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"]

@ is a charachter, | is a border and " " is an empty space. A user enters input to choose how much @ moves to the right and a new image is displayed that shows the new location of @ and the old location of @ is replaced with a space. The length of the list remains constant. This is the context of my question.

like image 786
SeesSound Avatar asked Nov 22 '12 23:11

SeesSound


1 Answers

You can simply find the index of the second occurrence by traversing the list and storing the indexes whose elements are 'a' until you've found two:

>>> appl = ['1', 'a', 'a', '2', 'a']
>>> idxs = (i for i,c in enumerate(appl) if c == 'a')
>>> next(idxs)
0
>>> appl[next(idxs)] = ''
>>> appl
['1', 'a', '', '2', 'a']
like image 119
phihag Avatar answered Sep 21 '22 12:09

phihag