What are ways we can combine different list slices?


#1

Question

In this code challenge, one possible way to remove an element might be by combining list slices. What are ways that we can combine list slices?

Answer

Since list slices are themselves lists, we can simply combine them as we would lists. The following are some ways you can use to combine different lists.

Say, for example, we have the following list and two list slices.

list = [1, 2, 3, 4, 5, 6]

list1 = list[:3] # [1, 2, 3]
list2 = list[4:] # [5, 6]

One way to combine them is using the + operator, which will create a new list with the first list’s elements followed by the second list’s elements. For example,

list2 + list1 # [5, 6, 1, 2, 3]

Another way to combine lists is using the .extend() method in Python. This method is applied to a list, and adds the elements from the list passed as an argument to the end of that list. This updates the list in-place.

list1.extend(list2)
print(list1) # [1, 2, 3, 5, 6]

One other way of combining lists is to utilize a loop. You can iterate over the elements of the list you are adding to the other list, and use .append() to add them one at a time. Like .extend(), .append() updates the list in-place.

for element in list2:
  list1.append(element)

print(list1) # [1, 2, 3, 5, 6]