0

How to replace all the values of a list upto a certain index to ceratin value or item? If the input is:

mylist = ['a', 'b', 'c', 'd']

Lets say the index we chose is 2 and we want to replace with $. So, the output should look like:

list_op = ['$', '$', '$', 'd']

Can we achive this python standar functions?

pault
  • 41,343
  • 15
  • 107
  • 149
idkman
  • 169
  • 1
  • 15

1 Answers1

1

you can use slice assignment:

lst = ["a", "b", "c", "d"]
lst[:3] = 3 * ["$"]
print(lst)  # ['$', '$', '$', 'd']

this means: replace the first 3 elemennts of lst (which is lst[:3]) with 3 * ["$"] (which is ['$', '$', '$']).

if you only wanted to replace the 2 middle elements:

lst[1:3] = 2 * ["$"]
# ['a', '$', '$', 'd']

also note that list is a built-in function in python and therefore not a good variable name.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111