user2996623
user2996623

Reputation: 1

Python, two dimensional list and coordinates

I have a two dimensional list:

def list():
    list1 =[1,2,3,4,5]
    list2 =[0,0,0,0,0]
    list3 =[6,7,8,9,10]

    list=[list1,list2,list3]

    for i in list:
        print(i)

list()

6 will have the coordinates (0,2), right?? I want to move 6 to (0,1) and when I do that, I also want (0,2) to become 0.

How do I do that? I have no idea.. I'm a beginner at this.

Upvotes: 0

Views: 5398

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122142

Just assign directly to those two index pairs, indexing from the outer list to the inner (the last list is 2, the middle list is 1), so the first element of the last list is at [2][0]:

outerlist[1][0], outerlist[2][0] = outerlist[2][0], 0

This assigns two values (one taken from outerlist[0][2], the other the literal 0 integer) to the two positions in the nested lists.

If you wanted to swap those two positions (taking the 0 from outerlist[0][1]), then do so with the same syntax:

outerlist[1][0], outerlist[2][0] = outerlist[2][0], outerlist[1][0]

because the right-hand side expression is evaluated before assigning the two values to the left-hand side targets:

>>> outerlist = [[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [6, 7, 8, 9, 10]]
>>> outerlist
[[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [6, 7, 8, 9, 10]]
>>> outerlist[1][0], outerlist[2][0] = outerlist[2][0], outerlist[1][0]
>>> outerlist
[[1, 2, 3, 4, 5], [6, 0, 0, 0, 0], [0, 7, 8, 9, 10]]

Upvotes: 1

Related Questions