1

Im trying to change a string in a list called lista composed by n times |_|, in a function I'm trying to change one specific place of the list with "X" but nothing is working

lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]

i want to change only the middle one to |X|

I already tried different methods like, the command replace or pop and then insert a new value but nothing as changed and always gives me an error

0stone0
  • 34,288
  • 4
  • 39
  • 64

3 Answers3

1

Use len(lista) // 2 to get the middle index.

Should there be an un-even number, // 2 will 'round' it to the previous integer, so 9 --> 4

lista = [ "|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|" ]
middle = len(lista) // 2

lista[middle] = '|X|'

print(lista)
['|_|', '|_|', '|_|', '|_|', '|_|', '|X|', '|_|', '|_|', '|_|', '|_|']

Try it online

0stone0
  • 34,288
  • 4
  • 39
  • 64
1
lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]
lista[ round(len(lista)/2)-1 ] = '|X|'

Output:

['|_|', '|_|', '|_|', '|_|', '|X|', '|_|', '|_|', '|_|', '|_|', '|_|']

Use -1 because indexes starts from 0

Will
  • 1,619
  • 5
  • 23
1

This code places "|X|" in the middle of the list:

if len(lista)%2==0:
    lista[int(len(lista)/2)-1]='|X|'
    lista[int(len(lista)/2)]='|X|'
else:
    lista[int(np.floor(len(lista)/2))]='|X|'

Output When len(lista)==10

['|_|', '|_|', '|_|', '|_|', '|X|', '|X|', '|_|', '|_|', '|_|', '|_|']

Output When len(lista)==11

['|_|', '|_|', '|_|', '|_|', '|_|', '|X|', '|_|', '|_|', '|_|', '|_|', '|_|']
Khaled DELLAL
  • 871
  • 4
  • 16