Goal: User can choose a section of the list via list slicing to change to ' '
Example of list
list=['a','','','','','','','','','','b','','','','','','','','','','c','','','']
user can choose Start and End of list slice (start=0 and end=12)
start=input("Where to start? ")
end=input("Where to end? ")
What I tried:
list[int(start):int(end)]=['']
Excepted result everything from 0:12 is changed to ' '
['','','','','','','','','','','','','','','','','','','','','c','','','']
Actual result everything from 0:12 was removed from the list
['', '', '', '', '', '', '', '', '', 'c', '', '', '']
Any ideas on how to get this to work and why the code of line I tried doesn't work?
CodePudding user response:
Firstly you shouldn't use keywords such as list
for variable names.
Here you are replacing a large slice of your list with a single element so to fix this repeat the element for the same length of the slice.
start = int(start)
end = int(end)
my_list[start:end] = ['']*(end - start)
If you havent come across multiplying a list before it just repeats the elements that many times so for example ["a", "b"]*3 == ["a","b","a","b","a","b"]
CodePudding user response:
You can use a while loop to solve this issue.
i = start
while i =< end:
list[i] = "whatever you want"
i = 1