Python Forum
Append only adding the same list again and again
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Append only adding the same list again and again
#4
Let me try a different way.

Line 37 creates a new square, and line 39 puts a link to that square into x.
Line 41 is the interesting bit. rotate_clockwise_90 is handed the square and it changes it. This change affects the reference to it in x. So x changes.
Line 43 then puts another link to the square in x. But this is the same link so all the elements in x are identical.

I think a good approach here is to make your functions not modify the data that is passed in That's easily done by making a copy early in the function. This approach is less memory efficient and would be a drawback for larger and more complex manipulations. But it does make them feel more like functions, where you don't expect the input to be modified.

For instance consider changing
def rotate_Clockwise_90(B):
    n1=len(B[0])
    ...
to

import copy
[...]
def rotate_Clockwise_90(B):
    B = copy.deepcopy(B)
    n1=len(B[0])
    ...
It's not the only way to go. You could instead make the copies in the main logic, allowing the functions to continue modifying the data. Either way is a possible solution.
Reply


Messages In This Thread
RE: Append only adding the same list again and again - by bowlofred - Jun-17-2020, 05:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 498 Mar-14-2024, 06:26 PM
Last Post: flash77
Question How to append integers from file to list? Milan 8 1,458 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  Adding values with reduce() function from the list of tuples kinimod 10 2,685 Jan-24-2023, 08:22 AM
Last Post: perfringo
  read a text file, find all integers, append to list oldtrafford 12 3,622 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  Using .append() with list vs dataframe Mark17 7 10,562 Jun-12-2022, 06:54 PM
Last Post: Mark17
  Adding a list to Python Emailing Script Cknutson575 4 2,331 Feb-18-2021, 09:13 AM
Last Post: buran
  adding numbers in a list Nickd12 2 2,212 Jan-15-2021, 12:46 PM
Last Post: Serafim
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 2,357 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  Adding List Element if Second part of the List Elements are the Same quest_ 3 2,477 Nov-25-2020, 04:33 PM
Last Post: bowlofred
  How to append to list a function output? rama27 5 6,776 Aug-24-2020, 10:53 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020