Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with List Reference
#1
Hello,

I am currently working on a school project where we should solve an 8-Puzzle (3x3 grid with 8 tiles. You can always move one tile to the empty spot). I created 2-dimensional list with numbers 1-8 + 0. 0 Marks the empty spot.

Now I am using the following code to move one tile (I want to move the 6 to 0 (and vice versa).

I know that I need to create a copy() of the list, so it is not referenced. But I still get the output wrong. It changes both lists.

I tried to find a solution to the problem, but all suggestions are to make a copy, what I am doing right now.

Thank you for any help!

Best regards,
NoLuck

My Code:
exampleState = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

movedState = exampleState.copy()



newList = exampleState.copy()

for i in range(len(newList)):
    for j in range(len(newList[i])):
        if newList[i][j] == 0:
            iPos = i
            jPos = j
    
numMove = int(movedState[iPos-1][jPos])
movedState[iPos][jPos] = int(numMove)
movedState[iPos-1][jPos] = 0
    
print("moved state:", movedState)
print("input state:", exampleState)
My Output:
Output:
moved state: [[1, 2, 3], [4, 5, 0], [7, 8, 6]] input state: [[1, 2, 3], [4, 5, 0], [7, 8, 6]]
Reply
#2
I figured that i should use
movedState = copy.deepcopy(exampleState)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unresolved reference problem john7 1 817 Oct-18-2022, 02:32 PM
Last Post: deanhystad
  Problem with "Number List" problem on HackerRank Pnerd 5 2,086 Apr-12-2022, 12:25 AM
Last Post: Pnerd
  How to define a variable in Python that points to or is a reference to a list member JeffDelmas 4 2,643 Feb-28-2021, 10:38 PM
Last Post: JeffDelmas
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,548 Sep-07-2020, 08:02 AM
Last Post: perfringo
  reference in pop function for linked list oloap 0 1,561 Mar-14-2020, 05:52 PM
Last Post: oloap
  set a new object node in a linked list via reference oloap 2 2,088 Mar-13-2020, 09:45 PM
Last Post: oloap
  Passing a list by reference virgik89 6 4,505 Jul-01-2018, 04:26 PM
Last Post: virgik89
  List 3 dimensions reference does not work Mario793 1 2,641 Mar-02-2018, 12:35 AM
Last Post: ka06059

Forum Jump:

User Panel Messages

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