- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Python Program to replace list elements within a range with a given number
When it is required to replace list elements within a range with a given number, list slicing is used.
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)
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]
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.
- Related Articles
- Python Program to replace elements of a list based on the comparison with a number
- Python program to generate random numbers within a given range and store in a list?
- Python Program to Replace Elements in a List
- Program to find number of pairs where elements square is within the given range in Python
- Python Generate random numbers within a given range and store in a list
- Java program to generate random numbers within a given range and store in a list
- Constrain a number within a given range in Arduino
- Program to update elements in a given range in Python
- How to print array elements within a given range using Numpy?
- Python Program for Number of elements with odd factors in the given range
- Java Program to Replace Elements in a List
- Java Program to create random BigInteger within a given range
- Golang Program to Print Odd Numbers Within a Given Range
- Style elements with a value within a specified range with CSS
- Python - Find the number of prime numbers within a given range of numbers