extend() – add all list entries to another list

In this code example, we add all list entries to another list. For this we use the extend() method.

Code Example

  1. The first line of the code creates a list named firstList and assigns it the values [1, 2, 3, 4].
  2. The second line of the code creates a list named secondList and assigns it the values [5, 6, 7, 8].
  3. The line firstList.extend(secondList) calls the extend method on the firstList object and passes secondList as an argument. The extend method is used to add the elements of one list to another list. In this case, all elements of secondList are added to the end of firstList.
  4. The for loop in the code iterates over the elements of the list firstList. For each iteration, the current element is stored in the variable i.
  5. The print function is used to print the current value of i during each iteration of the loop. The end parameter is set to a space character, so that the numbers are printed on the same line with a space between each number.
  6. The loop continues until all elements in firstList have been processed.

So, the code creates two lists, extends one list with the elements of the other list, and then prints all the elements of the extended list, separated by a space.

firstList = [1, 2, 3, 4]
secondList = [5, 6, 7, 8]


for i in firstList:
    print(i, end=" ")
1 2 3 4 5 6 7 8