Skip to content
Advertisement

How to remove a specific element from a 2d array in Python?

I am new to Python and now I’m trying to create a game called Pong

Everything looks to work fine but unfortunately, I can’t remove a specific element from 2D-Array /List once the ball touches a brick.

Here is my code:

class Brick:
    size = 5
    bricks = [[0] * size for i in range(size)] 

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def createBricks(self):
        for x in range(self.size):
            for y in range(self.size):
                self.bricks[x][y] = Brick(x * 70, y * 40)

    def draw(self):
        for bricks in self.bricks:
            for brick in bricks:
                 rect(brick.x, brick.y, 50, 20)

In the following method, I want to remove the specific element:

#In my main class

def removeBrick():
    for elem in brick.bricks:
        for _brick in elem:
            if ball.touchesBrick(_brick.x, _brick.y):
               #Here I want to remove the element

I have tried many ways with remove() and del but as a result, I couldn’t solve it.

Thanks in advance.

Advertisement

Answer

using for loops just gives you a copy to the element (so you can’t modify it directly). To solve this problem, you should use the enumerate class:

def removeBrick():
    for elem in brick.bricks:
        for i, _brick in enumerate(elem):
            if ball.touchesBrick(_brick.x, _brick.y):
               _brick.pop(i)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement