append multiple elements to a list in python

To append multiple elements to a list in Python, you can use the extend method or the + operator.

Here is an example using the extend method:

main.py
my_list = [1, 2, 3]
new_elements = [4, 5, 6]
my_list.extend(new_elements)
print(my_list)
89 chars
5 lines

Output:

main.py
[1, 2, 3, 4, 5, 6]
19 chars
2 lines

And here is an example using the + operator:

main.py
my_list = [1, 2, 3]
new_elements = [4, 5, 6]
my_list += new_elements
print(my_list)
84 chars
5 lines

Output:

main.py
[1, 2, 3, 4, 5, 6]
19 chars
2 lines

Both methods will modify the original list by adding all the elements from the new elements list at the end.

related categories

gistlibby LogSnag