Editor settings

General settings

Save settings

Learn to program with Python

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_list should become ["A", "B", "C", "D", "E", "F"]
  • Use the function extend()
  • Do not change the first line of code
Output will be displayed here