Reputation: 95
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
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
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