Intern
How to add a value to the end of a list in Python?
sobes.tech AI
Answer from AI
To add a value to the end of a list in Python, the append() method is used.
# Create a list
my_list = [1, 2, 3]
# Add the value 4 to the end of the list
my_list.append(4)
# Print the updated list
print(my_list)
You can also use slices with assignment, but this is less idiomatic for simple appending to the end.
# Create a list
my_list = [1, 2, 3]
# Add the value 4 to the end of the list using a slice
my_list[len(my_list):] = [4]
# Print the updated list
print(my_list)
The append() method is the most common and recommended way, as it is more readable and usually more efficient.