#Learn 🧠🐍#python: Sometimes when programming in python they're situations when you want to copy the contents of an existing list into another. Python has several ways of achieving that. In this thread you will learn different ways of achieving that with the help of examples.
1) Using the equal (=) sign operator:
Using = operator you can copy the contents of an existing list onto another/new list. But there's a problem with this method which I will explain on the next section.
The problem with the above method is that if you modify the new copied_fruits list the original list (fruits) is modified too, this is because the copied list (copied_fruits) is referencing/ pointing to same fruits list in memory.
How ever if you want the old list to remain unchanged if the new list is changed. You can either use one of the following options/methods below
2) Copy list using list slicing:
What is List Slicing?
List slicing refers to accessing a specific portion or a subset of the list for some operation while the original list remains unaffected.
The slicing operator in python can take 3 parameters out of which 2 are optional depending on the requirement.
Passing two colons to the list indicates that there is no limit on the start, stop and step indices. Hence, all the elements present in the fruits list are copied to the copied_fruits list.
3) Using list.copy() method:
the copy method doesn't take any parameters or modify the original list. It just returns the new list.
4) Using list comprehension
List comprehension in Python is an easy and compact syntax for creating a list from a string or another list.
It is a very concise and another elegant way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.
5) Using the copy module:
In Python, there are other two ways to create copies:
- Shallow Copy:
- Deep Copy
To make these copy work, we use the copy module.
Shallow Copy
A shallow copy doesn't create a copy of nested lists, instead it just copies the reference of nested objects. This means, a copy process does not recurse or create copies of nested objects/lists itself.
Deep Copy
A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements.
Finally 6) Using the list() constructor:
The list() constructor takes a single argument/parameter:
iterable (optional) - this is an object that could be a sequence (string, tuples, lists) or collection (set, dictionary) or any iterator object.
If iterable is passed as a parameter, it creates a list consisting of iterable's items and returns a new list of the items.
Congrats if you have reached this far. If you feel you have learned something new or find this thread useful to you, consider , liking, retweeting, commenting and following us for more useful programming, python, linux, shell scripting, cybersecurity tweets.