Sunday, January 11, 2009

Jython 101 - Altering Tuple Values

Often times we use lists and tuples to hold data that will be used at some later point in an application. When we iterate through the data within them without changing it then they work without any issues. However, if we wish to change one or two of the values that are contained in a tuple then we may run into an issue because they are immutable in the Jython world. Lists are a bit different as they can be altered. If you've run into this issue with tuples and need an easy solution, then hopefully the technique which I am about to describe will help you.

The Problem

Let's say we have a tuple of parameters that we wish to pass to another Jython module at some later point. However, once the receiving function obtains the tuple of parameters, it is found that a value needs to be added to it in order to make it complete. How do we add or insert a value into a tuple if they are immutable?


The Solution


Quite easily actually, the answer is that we define a list that will take the values of the tuple and pass it on.

For instance, lets define tuple:

x = ("one", "two", "four")

print x
['one', 'two', four']


If we try to alter the tuple and insert the value "three" before the four, we receive an error:


x[2] = "three"

TypeError: can't assign to immutable object



Therefore, a great workaround is to define an empty list and populate it with the contents of the tuple. At the same time, you can add, change, or remove any elements that you wish. In the end, use the newly define list as your "new" parameter list and pass it on.



# define empty list
y = []

# iterate through tuple and populate new list

for elem in x:

# check element to see if it's contents need to be changed, or moved
# in this case, we are looking for an element with the value "four"
# so that we can insert "three" in front of it

if elem == "four":

# Insert the new element, and then the current element
y.append("three")
y.append(elem)
else:
# Insert the current element
y.append(elem)

print y # Use the new list and continue.
['one', 'two', 'three', 'four']




I hope that you find this tip for using Jython tuples useful.

No comments:

Post a Comment

Please leave a comment...