Python: Append items to a tuple
Tuples, tuples, tuples. Thats fun to say. We’ve all used them, but dynamic assembly of them? Now this is cool — and something I never needed to do until today of course. Appending values to a list, or a dict is easy and well documented, but less common is the need to append or dynamically assemble a tuple. Lets look at a Pythonic way to do that.
But why? (You should always ask this) In my use-case, I was dynamically assembling an sql query. based on the existence of a form variable, i needed to add a clause to my sql, which I am doing classic pythonic replacement on using a tuple of values.
Here is the deal — when you set your first value, simply put it in parens with a trailing comma like so:
myTuple = (‘first item’,)
Notice the trailing comma!
Now to add items to it, assign the tuple with the + operator:
myTuple = myTuple + (‘second item’,)
Again, notice the trailing comma! This works in sequential code or loops.
Now if you output your Tuple, you get:
>>> myTuple
(‘first item’, ‘second item’)
So for my use case, then I can use it in a SQL statement like so:
sql = “SELECT * from table WHERE col1=%s and col2=%s”
db.engine.execute(sql, myTuple)
There you have it. Not difficult at all, but I never came across this before, so I am blogging about it to a) help others, and b) have a place to look it up when I forgot.
Ciao