avatar

Python Course #12: Pass by Assignment, Copy, Reference, and None

Now that the you know what mutable (e.g. lists , sets and dictionaries ) and immutable data types (e.g. tuples ) are it is important to talk about copies, references and None .

Python Pass by Assignment

When you call a pass data to a function such as print(...) there are two ways. The first option is to pass the data directly as a value:

The second option is to pass the data as a variable:

The difference between those two options is that the second option allows you to access the data you passed to the function later in your program by stating the variable. When the function that receives the data modifies it internally, you have to be aware of two critical things:

When a primitive data type ( bool , int , float , and str ) or immutable data type (e.g. tuple ) is passed to a function, its value is copied. Therefore, all changes made inside a function won’t affect the values stored in the variables passed to the function. This is called pass by value .

When a mutable data type (e.g. list , set , dict ) is passed to a function, the data isn’t copied. Because of this, changes that are made inside the function affect the values outside of the function. This is called pass by reference

This sounds pretty theoretical, so here comes an example:

Even though you haven’t learned about declaring functions in Python this example declares the function func(x, y) that takes two parameters. func(x, y) subtracts 1 from the first parameter, and calls pop() on the second one. That is everything you need to understand at the moment.

In the main program, the int i and the list l are declared and then passed to func(x, y) . When looking at i and l after func(x, y) has been executed, you can see that i is still 1 and not 0 because i ’s value was copied. However, l is missing its last element since it was passed as a reference.

This mix of pass by value and pass by reference in Python is called pass by assignment . It is essential to keep this concept always in mind when writing Python code.

In the previous parts of this Python course, you have seen that it is possible to get a copy of a mutable data type by calling the .copy() function:

By using .copy() , the data outside of the function isn’t changed.

In the following example the difference between a copy and reference is further amplified:

In the first line the list ['a', 'b', 'c'] is declared and than a new reference to this list is created with l = . In the second line another reference to the list ['a', 'b', 'c'] is created with: m = l . In the third line the list is copied and a reference to that copy is created with: n = l.copy() .

There are three references to two lists with the same content. l and m reference the first list and n reference the second list . Because l and m reference the same list every modification done using l or m will always be reflected in both. n won’t change as it references a different list .

Python is vs ==

To check if two variables reference the same value you can use the is operator to compare the values use the == operator:

l is n evaluates to False because they reference differnt list s, however, those two list s contain the same values and therefore l == n evaluates to True . You can also check the id that a variable is referencing using id(...) :

You can see that the id of l and m is the same and the id of n is different (The numbers are different everytime you run this code). The is operator is actually implemented using == with id(...) == id(...) .

Python None

Now that you know the difference between a copy and a reference, there is one last thing to talk about: ` None . The keyword None in Python indicates no value at all. And there is only one None`:

None can be used to initialize a variable without assigning a value. This can be useful when the value of a variable is assigned under a condition:

None actually has it’s own type and is an immutable data type because it can’t be changed:

None concludes this article. Throughout this Python course, you will come across pass by assignment, copies, references, and None reasonably often. Make sure to get the free Python Cheat Sheets in my Gumroad shop . If you have any questions about this article, feel free to join our Discord community to ask them over there.

Further Reading

Big o notation explained.

Why is Big O Notation Used? When you got different algorithms to solve the same problem, you need to compare those to each other to pick the best (meaning fastest) for your program. Looking at eac...

Python Course #2: Variables and Primitive Datatypes for Absolute Beginners

After you have written your first Python Hello World program (find the article over here: Python Lesson 1: Your First Python Program (Complete Beginners Guide) ) it is time to talk about variables ...

Python Course #3: Introduction to Boolean Algebra

The term Boolean algebra itself might sound dry and dull, but it is one of the backbones of all the computers we use today. In this article, you will learn what Boolean algebra is and how to use it...

Estimate Gas in Ethereum Transactions with Python web3 and brownie

Change Windows 10/11 Display Resolution with a Python System Tray Application

Trending Tags

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • numpy.vdot() in Python
  • Python | sympy.multiplicity() method
  • Page Rank Algorithm and Implementation
  • Datagram in Python
  • How to Use Google Bard with Python
  • PYGLET – Creating File Location
  • Returning Multiple Values in Python
  • String Template Class in Python
  • numpy.dot() in Python
  • Changing Class Members in Python
  • Unit Testing in Python - Unittest
  • Quine in Python
  • Logical Operations on String in Python
  • Tensorflow - linspace() in Python
  • Biopython - Sequence Operations
  • numpy.signbit() in Python
  • First Class functions in Python
  • Using Else Conditional Statement With For loop in Python
  • Program to access different columns of a multidimensional Numpy array

copy in Python (Deep Copy and Shallow Copy)

In Python , Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create “real copies” or “clones” of these objects, we can use the copy module in Python .

Syntax of Python Deepcopy

Syntax: copy.deepcopy(x)

Syntax of Python Shallowcopy

Syntax: copy.copy(x)

In order to make these copies, we use the copy module. The copy() returns a shallow copy of the list, and deepcopy() returns a deep copy of the list. As you can see that both have the same value but have different IDs.

Example: This code showcases the usage of the copy module to create both shallow and deep copies of a nested list li1 . A shallow copy, li2 , is created using copy.copy() , preserving the top-level structure but sharing references to the inner lists. A deep copy, li3 , is created using copy.deepcopy() , resulting in a completely independent copy of li1 , including all nested elements. The code prints the IDs and values of li2 and li3 , highlighting the distinction between shallow and deep copies in terms of reference and independence.

What is Deep copy in Python?

A deep copy creates a new compound object before inserting copies of the items found in the original into it in a recursive manner. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object.  

Deep copy in Python

In the above example, the change made in the list did not affect other lists, indicating the list is deeply copied.  

This code illustrates deep copying of a list with nested elements using the copy module. It initially prints the original elements of li1 , then deep copies them to create li2 . A modification to an element in li2 does not affect li1 , as demonstrated by the separate printouts. This highlights how deep copying creates an independent copy, preserving the original list’s contents even after changes to the copy.

What is Shallow copy in Python?

A shallow copy creates a new compound object and then references the objects contained in the original within it, which means it constructs a new collection object and then populates it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of an object is copied into another object. It means that any changes made to a copy of an object do reflect in the original object. In python, this is implemented using the “ copy() ” function. 

Shallow copy in Python

In this example, the change made in the list did affect another list, indicating the list is shallowly copied. Important Points: The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Example: This code demonstrates shallow copying of a list with nested elements using the ‘ copy' module. Initially, it prints the original elements of li1 , then performs shallow copying into li2 . Modifying an element in li2 affects the corresponding element in li1, as both lists share references to the inner lists. This illustrates that shallow copying creates a new list, but it doesn’t provide complete independence for nested elements.

RECOMMENDED ARTICLES – Difference between Shallow and Deep copy of a class

Please Login to comment...

  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Copy a File in Python

    python assignment copy

  2. Python Copy File (Examples)

    python assignment copy

  3. Multiple of 3 in Python

    python assignment copy

  4. Copy List in Python

    python assignment copy

  5. First And Last Digits In Python

    python assignment copy

  6. Double Char In Python

    python assignment copy

VIDEO

  1. How to use assignment operators in #python

  2. Python Assignment 2

  3. Python Assignment Operators And Comparison Operators

  4. Week 3 graded assignment python #python #iitm

  5. Python Assignment 2

  6. Python Assignment 2

COMMENTS

  1. Python: Assignment vs Shallow Copy vs Deep Copy

    In Python 3, you can use list.copy (). However, I prefer the equivalent expression list [:] because it works in both Python 2 and 3. Shallow copy is different from assignment in that it creates a ...

  2. Python Course #12: Pass by Assignment, Copy ...

    This mix of pass by value and pass by reference in Python is called pass by assignment. It is essential to keep this concept always in mind when writing Python code. In the previous parts of this Python course, you have seen that it is possible to get a copy of a mutable data type by calling the .copy () function: 1.

  3. copy in Python (Deep Copy and Shallow Copy)

    In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create “real copies” or “clones” of these objects, we can use the copy module in Python. Syntax of Python Deepcopy