Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract one from every value in a tuple in Python?

I have a tuple created with zip() and I need to subtract one from each integer in the tuple. I tried the following but apparently it only works on lists, so how would I adapt this for tuples in Python?

[...]
lower, upper = zip(*table)
lower[:] = [x + 1 for x in lower]
upper[:] = [x - 1 for x in upper]
holes = zip(lower[:-1], upper[1:])

TypeError: 'tuple' object does not support item assignment

Big picture is I have a series of non-overlapping sorted intervals stored in table and I need to get the series of holes. E.g. my intervals table could be:

[ 6,  7]
[ 8,  9]
[14, 18]
[23, 32]

And I want to compute the holes in between the intervals:

[10, 13]
[19, 22]
like image 837
WilliamKF Avatar asked Feb 13 '13 21:02

WilliamKF


2 Answers

Use the tuple constructor with a generator expression:

lower = tuple(x - 1 for x in lower)
upper = tuple(x + 1 for x in upper)
like image 61
nneonneo Avatar answered Sep 28 '22 15:09

nneonneo


You can also just work these out in a single list comprehension:

holes = [(table[i][1]+1, table[i+1][0]-1) for i in range(len(table)-1)]
like image 24
John La Rooy Avatar answered Sep 28 '22 17:09

John La Rooy