Daymor
Daymor

Reputation: 95

Adding the tuple values into another tuple...but added 1

I'm using 1 tuple and i want to create 4 tuple variations of the tuple I'm using. Example:

a=(x,y)

and i want to make

b=(x+1,y)
c=(x,y+1)

etc etc

Since I cant change a tuple, any ideas on how to do this?

Upvotes: 0

Views: 199

Answers (3)

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

def next_to(t, min_x=0, max_x=4, min_y=0, max_y=4):
    x,y = t

    for dx,dy in [(-1,0), (1,0), (0,-1), (0,1)]:
        if (min_x <= x+dx < max_x) and (min_y <= y+dy < max_y):
            yield (x+dx, y+dy)

for t in next_to( (2,2) ):
    print t

results in

(1, 2)
(3, 2)
(2, 1)
(2, 3)

Upvotes: 0

Kabie
Kabie

Reputation: 10663

You mean this?

b=(a[0]+1,a[1])
c=(a[0],a[1]+1)

Upvotes: 0

moinudin
moinudin

Reputation: 138357

While you cannot modify an existing tuple, you can create a new tuple based on an existing tuple's values. I think something like this might be what you want:

>>> a = (1, 2)
>>> [(a[0]+dx, a[1]+dy) for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]]
[(0, 2), (2, 2), (1, 3), (1, 1)]

This creates the four tuples each one shifting either x or y in either direction using a list comprehension.

Upvotes: 3

Related Questions