# Python Program to replace list elements within a range with a given number

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

When it is required to replace list elements within a range with a given number, list slicing is used.

## Example

Below is a demonstration of the same

my_list = [42, 42, 18, 73, 11, 28, 29, 0, 10, 16, 22, 53, 41]

print("The list is :")
print(my_list)

i, j = 4, 8
my_key = 9

my_list[i:j] = [my_key] * (j - i)

print("The result is:")
print(my_list)

## Output

The list is :
[42, 42, 18, 73, 11, 28, 29, 0, 10, 16, 22, 53, 41]
The result is:
[42, 42, 18, 73, 9, 9, 9, 9, 10, 16, 22, 53, 41]

## Explanation

• A list is defined and is displayed on the console.

• Two integers are defined, and an integer is defined.

• The key is multiplied with the difference between the two integers.

• It is assigned to the sliced indices.

• This is the output that is displayed on the console.

Updated on 15-Sep-2021 12:35:37