user3308780
user3308780

Reputation: 45

Python: how to revise tuples in an list?

I have a list of x,y tuples. Think of these original tuples as being a change in x and y. I wish to apply these subsequent changes in x and y to the previous tuple. For ex, after the zero term, x gained 100 and y stayed the same. Thus the new first term would be (100,100). After that, x stayed the same and y decreased by 100. Applying that to the revised first term would result in a revised second term of (100,0) and etc.

xy = [(0,100), (100,0), (0,-100), (-100,0)]

This is the desired result:

xy = [(0,100), (100,100), (100,0), (0,0)]

How to work around the immutabilty of lists? How do I get this done in a loop?

Upvotes: 0

Views: 143

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121634

The list itself is still mutable; just replace the tuples with new ones:

x, y = 0, 0
for i, (dx, dy) in enumerate(xy):
    x += dx
    y += dy
    xy[i] = (x, y)

Demo:

>>> xy = [(0, 100), (100, 0), (0, -100), (-100, 0)]
>>> x, y = 0, 0
>>> for i, (dx, dy) in enumerate(xy):
...     x += dx
...     y += dy
...     xy[i] = (x, y)
... 
>>> xy
[(0, 100), (100, 100), (100, 0), (0, 0)]

Upvotes: 5

Related Questions