How to assign one value to the entire (or partial) list in Python?
list, python, variable-assignment
Solution
You can actually use the slice assignment mechanism to assign to part of the list.
>>> some_list = [0, 1, 2, 3]
>>> some_list[:1] = [5]*1
>>> some_list[1:] = [6]*3
>>> some_list
[5, 6, 6, 6]
This is beneficial if you are updating the same list, but in case you want to create a new list, you can simply create a new list based on your criteria by concatenation
>>> [5]*1 + [6]*3
[5, 6, 6, 6]
You can wrap it over to a function
>>> def YourAnswer(lst, repl, index, size):
lst[index:index + size] = [repl] * size
>>> some_list = [0, 1, 2, 3]
>>> YourAnswer(some_list, 6, 1, 3)
>>> some_list
[0, 6, 6, 6]
Problem
I have `List = [0, 1, 2, 3]` and I want to assign all of them a number say, 5: `List = [5, 5, 5, 5]`. I know I can do `List = [5] * 4` easily. But I also want to be able to assign say, 6 to the last 3 elements. ``` List = [5, 5, 5, 5] YourAnswer(List, 6, 1, 3) >> [5, 6, 6, 6] ``` where `YourAnswer` is a function. Anything similar would be helpful. Prefer to avoid for-loop. But if there is no known possibility, please tell me.