HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Python - Change List Items


Example
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']  

my_list[0] = 'apricot'
my_list[2] = 'grape'
my_list[-1] = 'fig'

print(my_list)  # Output: ['apricot', 'banana', 'grape', 'date', 'fig']

             

Changing multiple items using slicing

Example
my_list[1:3] = ['orange', 'lemon']
print(my_list)  # Output: ['apricot', 'orange', 'lemon', 'date', 'fig']
             

Changing multiple items with different lengths

Example
my_list[1:4] = ['peach']  # Replacing three elements with one
print(my_list)  # Output: ['apricot', 'peach', 'fig']
             

Changing multiple items with different lengths using slicing

Example
my_list[1:3] = ['plum', 'quince', 'raspberry']  # Replacing two elements with three
print(my_list)  # Output: ['apricot', 'plum', 'quince', 'raspberry']
             

Changing items with step

Example
my_list[::2] = ['blueberry', 'blackberry', 'boysenberry']
print(my_list)  # Output: ['blueberry', 'plum', 'blackberry', 'raspberry', 'boysenberry']