- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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.
Advertisements