Hinam Mehra
Hinam Mehra

Reputation: 73

Change the values in a tuple in a list

I have a two-dimensional list containing three-element tuple.

image = [[(15, 103, 255), (0, 3, 19)],[(22, 200, 1), (8, 8, 8)],[(0, 0, 0), (5, 123, 19)]]

I want to add one to each element.

def get_elements(image):
    for i in range(len(image)-1) :
        m = image[i]
        for j in range(len(m)-1) :
            n = image[j]
            for k in range(len(n)-1) :
                ans = image[i][j][k]
                ans = ans+1
                return ans

This code just adds one to the first element and returns 15 + 1 = 16. I want it to give:

image = [[(16, 104, 256), (1, 4, 20)],[(23, 201, 2), (9, 9, 9)],[(1, 1, 1), (6, 124, 20)]]

Upvotes: 3

Views: 263

Answers (2)

John La Rooy
John La Rooy

Reputation: 304137

If you are doing image manipulation, you should consider numpy

>>> import numpy as np
>>> image = np.array([[(15, 103, 255), (0, 3, 19)],[(22, 200, 1), (8, 8, 8)],[(0, 0, 0), (5, 123, 19)]])
>>> image + 1
array([[[ 16, 104, 256],
        [  1,   4,  20]],

       [[ 23, 201,   2],
        [  9,   9,   9]],

       [[  1,   1,   1],
        [  6, 124,  20]]])

numpy already has this common sense definition of adding 1 to an array

Upvotes: 4

John Kugelman
John Kugelman

Reputation: 361585

Tuples are immutable. You can't modify them directly, so the best bet is to generate a new list with new tuples.

>>> image
[[(15, 103, 255), (0, 3, 19)], [(22, 200, 1), (8, 8, 8)], [(0, 0, 0), (5, 123, 19)]]
>>> [[(r+1,g+1,b+1) for r,g,b in row] for row in image]
[[(16, 104, 256), (1, 4, 20)], [(23, 201, 2), (9, 9, 9)], [(1, 1, 1), (6, 124, 20)]]

This uses two nested list comprehensions. The outer one loops over each row, yielding a new replacement row each iteration (here denoted [...]):

[[...] for row in image]

The inner one loops over the pixels in each row, yielding new tuples with modified RGB values.

[(r+1,g+1,b+1) for r,g,b in row]

Upvotes: 10

Related Questions