PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] How to pass 2d array in python by value and not by reference?

 July 06, 2022     arrays, pass-by-reference, python     No comments   

Issue

I have a 2D array that I need to constantly update and assign to different variables but the update has to take place from the initial array. Since lists are passed by reference and not by value the regular assignment does not work. I tried: list1 = list2[:] which works perfectly fine with a 1D arrays but not with a 2D array.

Has anyone encountered this before?


Solution

Python Shallow and Deep Copy

As you said, this kind of assignment is done by reference and not by value. In order to assign mutable data types like lists, numpy arrays and etc. by value, you have to use Python Copy Module. This module provides you with two shallow and deep copy methods that you should chose one of them according to the type of data which you are going to copy. If the object you are going to copy includes another objects like list, classes and ... in itself, you should use deep copy method otherwise, shallow copy should be used (In the above described problem, it seems shallow copy is what you are looking for).



Answered By - Arashsyh
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing