Search code examples
pythonlistvariable-assignment

How to assign one value to the entire (or partial) list in Python?


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]

How can such a YourAnswer function be implemented, preferably without a for loop?


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]