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:
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 + list2combines the items from both lists intolist3.
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:
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
list2and appends it tolist1.
Method 3: Using the extend() Method
You can also use the extend() method to add elements from one list to another.
Example Code:
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 oflist2to the end oflist1.
Try It Yourself: Fun Exercises
- Combine Your Hobbies:
- Create two lists of your hobbies.
- Use the
+operator to combine them into a single list.
- 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!