Join Lists

 

What You'll Learn: In this tutorial, you'll discover different ways to join, or concatenate, two or more lists in Python. Joining lists allows you to combine their items into a single list.

Method 1: Using the + Operator

One of the easiest ways to join two lists is by using the + operator.

Example Code:

python
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

Output: ['a', 'b', 'c', 1, 2, 3]
 

What's Happening Here?

  • list1 + list2 combines the items from both lists into list3.

Method 2: Using a For Loop

Another way to join two lists is by appending all the items from one list into another, one by one.

Example Code:

python
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
    list1.append(x)
print(list1)

Output: ['a', 'b', 'c', 1, 2, 3]
 

What's Happening Here?

  • The for loop goes through each item in list2 and appends it to list1.

Method 3: Using the extend() Method

You can also use the extend() method to add elements from one list to another.

Example Code:

python
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)

Output: ['a', 'b', 'c', 1, 2, 3]
 

What's Happening Here?

  • list1.extend(list2) adds all the elements of list2 to the end of list1.

Try It Yourself: Fun Exercises

  1. Combine Your Hobbies:
    • Create two lists of your hobbies.
    • Use the + operator to combine them into a single list.
  2. Join Your Favorite Books and Movies:
    • Make one list of your favorite books and another of your favorite movies.
    • Use the extend() method to create one list that includes both books and movies.

Summary:

In this Python tutorial, we learned how to join lists using three methods: the + operator, a for loop with append(), and the extend() method. Joining lists is a useful way to combine multiple collections of items into one. Keep experimenting and have fun with lists in Python!