Adding multiple elements to a list #
You can only add one item at a time with the function append(). However, we can add multiple elements to the end of a list using the extend() function with a list as an argument.
For example:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # [1, 2, 3, 4, 5]
Difference between append() and extend() #
append()takes one argument of any type and adds it to the end of a list.extend()takes one list as an argument and adds each item to the end of a list.
For example:
my_list = [1,2,3]
my_list.append([4, 5])
print(my_list) # output: [1, 2, 3, [4, 5]]
another_list = [1,2,3]
another_list.extend([4, 5])
print(another_list) # output: [1, 2, 3, 4, 5]
From the example above, my_list after append will have a length of 4 with the last element being the added list, while another_list will have a length of 5 from adding 2 elements to it.
Exercise #
Use the function extend() to add items ["E", "F"] to the variable my_list
Tests #
my_listshould become["A", "B", "C", "D", "E", "F"]- Use the function
extend() - Do not change the first line of code
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules