Copy Lists
What You'll Learn: In this tutorial, you'll discover different ways to copy a list in Python. Copying lists allows you to create a separate list with the same items, without linking them together.
Why Not Just Use Assignment?
You can't simply copy a list by typing list2 = list1. This will only create a reference to list1, meaning changes to list1 will also affect list2.
Method 1: Use the copy() Method
You can use the built-in copy() method to create a copy of a list.
Example Code:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output: ['apple', 'banana', 'cherry']
What's Happening Here?
thislist.copy()creates a new listmylistthat is a copy ofthislist.
Method 2: Use the list() Method
Another way to make a copy is to use the built-in list() method.
Example Code:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Output: ['apple', 'banana', 'cherry']
What's Happening Here?
list(thislist)creates a new listmylistthat is a copy ofthislist.
Method 3: Use the Slice Operator
You can also make a copy of a list by using the slice operator [:].
Example Code:
thislist = ["apple", "banana", "cherry"]
mylist = thislist[:]
print(mylist)
Output: ['apple', 'banana', 'cherry']
What's Happening Here?
thislist[:]creates a new listmylistthat is a copy ofthislist.
Try It Yourself: Fun Exercises
- Copy Your Favorite Movies List:
- Create a list of your favorite movies.
- Use the
copy()method to create a duplicate list.
- Duplicate Your Snack List:
- Make a list of snacks.
- Use the
list()method to copy the list.
- Clone Your Book List:
- Write a list of books you want to read.
- Use the slice operator
[:]to clone the list.
Summary:
In this Python tutorial, we learned different ways to copy a list using the copy() method, list() method, and the slice operator [:]. Copying lists allows you to create separate lists with the same items, without affecting each other. Keep experimenting and have fun with lists in Python!