Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] List Changes After Assignment — How to Clone or Copy It?

#1
List Changes After Assignment — How to Clone or Copy It?

Problem: If you assign a list object to a new variable using new_list = old_list, any modification to new_list changes old_list. What’s the reason for this and how can you clone or copy the list to prevent this problem?

Example: Let’s consider the following example.

old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list
new_list.append(42)
print(old_list)
# ['Alice', 'Bob', 'Carl', 42]

Appending an element to the new_list also modifies the original list old_list. Thus, old_list has now four elements—even though you didn’t change it directly.

Explanation


This problem of simultaneously modifying “two” lists arises because you don’t have two lists but only a single one.

In Python, everything is an object. You create a new list object ['Alice', 'Bob', 'Carl'] that resides in your machine’s memory. Both variable names new_list and old_list point to the same object in memory—if you modify one, you also modify the other!

List Changes After Assignment -- How to Clone or Copy It?https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" />

The following interactive tool visualizes the memory used by the Python interpreter when executing this particular code snippet:

Exercise: Visualize how the problem arises by clicking “Next”.

Do you understand the source of the problem? Great, let’s dive into the solutions starting with a short overview!

Solution Overview


You can see all three solutions discussed in this tutorial in our interactive Python shell:

Exercise: Change the original list. Do all three methods still produce the same output?

Next, you’ll learn about each method in greater detail!

Method 1: Slicing


The easiest way to create a shallow copy of a Python list is via slicing:

# Method 1: Slicing
old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list[:]
new_list.append(42)
print(new_list)
# ['Alice', 'Bob', 'Carl']

The slicing operation old_list[:] creates a new list, so the variables new_list and old_list now point to different objects in memory. If you change one, the other doesn’t change.

This is the way with the least amount of characters and many Python coders would consider this the most Pythonic one. If you want to learn more about slicing, watch the following video and dive into the detailed blog tutorial.

Related Tutorial: Introduction to Slicing in Python



Method 2: Copy


An alternative is to use the list.copy() method that creates a shallow copy of the list.

# Method 2: Copy
old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list.copy()
new_list.append(42)
print(old_list)
# ['Alice', 'Bob', 'Carl']

The list.copy() method copies all list elements into a new list. The new list is the return value of the method. It’s a shallow copy—you copy only the object references to the list elements and not the objects themselves.

The result is the same as the slicing method: you have two variables pointing to two different list objects in memory.

You can learn more about the list.copy() method in my detailed blog tutorial and the following video:

Related Tutorial: Python list.copy() [Ultimate Guide]



Method 3: List Comprehension


A third way to solve the problem of two lists pointing to the same object in memory is the list comprehension way to create new lists.

# Method 3: List Comprehension
old_list = ['Alice', 'Bob', 'Carl']
new_list = [x for x in old_list]
new_list.append(42)
print(old_list)
# ['Alice', 'Bob', 'Carl']

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

You can watch the tutorial video and read over the related blog article to learn more about it!



Related Tutorial: An Introduction to List Comprehension

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post List Changes After Assignment — How to Clone or Copy It? first appeared on Finxter.



https://www.sickgaming.net/blog/2020/09/...r-copy-it/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Read a File Line-By-Line and Store Into a List? xSicKxBot 0 3 Yesterday, 06:12 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 33 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 32 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 38 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] How to Sort and Return a Python List in One Line? xSicKxBot 0 41 09-09-2020, 07:08 AM
Last Post: xSicKxBot
  [Tut] Python One Line Sum List xSicKxBot 0 35 09-08-2020, 06:43 PM
Last Post: xSicKxBot
  [Tut] How to Sort and Return a Python List in One Line? xSicKxBot 0 43 09-02-2020, 06:16 PM
Last Post: xSicKxBot
  [Tut] Python One Line Sum List xSicKxBot 0 46 09-01-2020, 03:28 PM
Last Post: xSicKxBot
  [Tut] How to Create a List of Dictionaries in Python? xSicKxBot 0 95 07-09-2020, 11:37 AM
Last Post: xSicKxBot
  [Tut] Zip With List Output Instead of Tuple | Most Pythonic Way xSicKxBot 0 98 07-08-2020, 05:41 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
(Indie Deal) FREE Ghost Sweeper, ? NBA 2...
Last Post: xSicKxBot
Today 08:16 AM
» Replies: 0
» Views: 3
(Free Game Key) BigFish Game of Your Cho...
Last Post: xSicKxBot
Today 08:16 AM
» Replies: 0
» Views: 4
News - Random: Not Everyone Is Happy Wit...
Last Post: xSicKxBot
Today 08:15 AM
» Replies: 0
» Views: 2
News - Xbox Could Offer Streaming Stick ...
Last Post: xSicKxBot
Today 08:15 AM
» Replies: 0
» Views: 3
microStudio Game Engine Hands-On
Last Post: xSicKxBot
Today 12:22 AM
» Replies: 0
» Views: 4
Fedora - Contribute at the Fedora Test W...
Last Post: xSicKxBot
Today 12:22 AM
» Replies: 0
» Views: 3
News - Review: Pumpkin Jack – The Perfec...
Last Post: xSicKxBot
Today 12:22 AM
» Replies: 0
» Views: 3
News - Marvel's Spider-Man: Miles Morale...
Last Post: xSicKxBot
Today 12:22 AM
» Replies: 0
» Views: 4
[Tut] How to Read a File Line-By-Line an...
Last Post: xSicKxBot
Yesterday 06:12 PM
» Replies: 0
» Views: 3
(Indie Deal) Alien Cat Bundle, RIDE 4 re...
Last Post: xSicKxBot
Yesterday 06:11 PM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020