Monday, May 18, 2009

Python, nesting tuples

As already discussed in a previous post you can use a tuple in Python. A tuple is in basic a list which content can not be changed. A tuple can have elements of all kind of variable types. This includes an other tuple. What this means is that a list can have a list as one of the list items, or a tuple because we handling tuples in this post.

this sounds useful however you have to keep track of what is nested and where it is nested. in the example below you can see how a tuple is nested in an other tuple. First we create a tuple named sometuple and after that we create a second tuple which as first element will have the tuple sometuple as a element.

sometuple = ("value0","value1","value2","value3","value4")
someothertuple = (sometuple,"value5","value6")

Now if we do a print of "someothertuple" like in the example below we get all the elements. which will be in this case:

print someothertuple[:]
(('value0', 'value1', 'value2', 'value3', 'value4'), 'value5', 'value6')

As we know that the first element of the tuple is a tuple we can get only the first element and get a other result:

print someothertuple[0]
('value0', 'value1', 'value2', 'value3', 'value4')


now if we want the second element of the tuple which himself is a element of a tuple we can do this as followed:

print someothertuple[0][1]
value1

As you can see this can become quite confusing when you start nesting a lot of tuples in tuples so in most cases this is not a good idea. However there are some situations where it can be used. Think about creating a static table which holds basic information about a chess board and what fields are black and which are white. You can calculate this also but you can also use nested tuples. You can also use it for example to create a layout for a playfield for a game... where can a player stand and where not. You have to remember that a tuple can NOT be updated so you can not use it to keep track of where a player is or how chess pieces are arranged. However for basic layout of your grid it can be used.


3 comments:

Paddy3118 said...

Hi Johan,
Just a small comment, your statement:

print someothertuple[:]

Could be written as:

print someothertuple

- Thanks.

Johan Louwers said...

Hi Paddy,
you are correct... that is also a way of writing it.. I think it is a taste thing... both statements work ;-)

regards,
Johan Louwers

Anonymous said...

John , i am really following ur lessons step by step and i engoyed them so much

so thank u