August 30, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Learn to Program Using Python: Indexing Nested Tuples

  • June 22, 2004
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »


Preface

This document is part of a series of online tutorial lessons designed to teach you how to program using the Python scripting language.  The ultimate objective is to progress to JPython, forming the link between Python and Java.

Viewing tip

You may find it useful to open another copy of this lesson in a separate browser window.  That will make it easier for you to scroll back and forth among the different listings while you are reading about them.

Something for everyone

Beginners start at the beginning, and experienced programmers jump in further along. Learn to Program using Python: Lesson 1, Getting Started provides an overall description of this online programming course.

Introduction

This is one in a series of lessons designed to teach you about tuples.

Previous lessons (see Learn to Program using Python: Unpacking Tuples ) have illustrated

  • How to create (pack) a tuple.
  • How to access a tuple item using indexing.
  • How to slice a tuple.
  • How to nest tuples.
  • How to create empty tuples.
  • How to create single-item tuples.
  • How to unpack a tuple
Preview

The primary purpose of this lesson is to teach you how to use multiple square-bracket notation for indexing nested tuples.

What Is a Tuple?

A tuple is an immutable ordered list of objects.  It can contain references to any type of object.  See Learn to Program using Python: Nested Tuples for a more detailed description.

Sample Program

Indexing a nested tuple

Listing 1 shows the beginning of a Python script that:

  • Packs a two-item tuple by applying the repeat operator to a single-item tuple.
  • Displays information about the two-item tuple by using the membership operation in the conditional clause of an if statement.
  • Packs a deeply-nested tuple by successively nesting tuples in new tuples.
  • Uses multiple square-bracket index notation to successively access and display information about the nested tuples.
# File Tuple05.py
#-------------------------------
t1 = "a",
t2 = t1*2

Listing 1

(Note that some of the text in the listings was highlighted using boldface for emphasis.)

The remaining parts of this program are shown as code fragments in subsequent listings.  A listing of the entire program is shown in Listing 15 near the end of the lesson.

Tuples support the repeat operator

As shown in Listing 1, tuples support the repeat (*) operator.

The repeat operator behaves like a form of concatenation.  You can cause a tuple to be concatenated onto itself a specified number of times using the syntax shown in the boldface line in Listing 1.

The operands

The left operand of the * operator specifies the tuple to be concatenated onto itself.  The integer right operand specifies the number of copies of the tuple that are to be concatenated together.

The tuple that resulted from performing this operation is shown displayed in boldface in Listing 3 later in the lesson.

Tuples support the membership operation

Tuples also support the membership (in) operation, as illustrated in boldface in Listing 2.
 

if ("b" in t2):
  print "OK"
if ("a" in t2):
  print "t2"
  print t2
  print "length = ",len(t2)

Listing 2

The membership operation is used twice in the code fragment shown in Listing 2.  In both cases, the membership operation is used in the conditional expression of an if statement.

The false case

In the first case, a test is made to determine if the tuple referred to by t2 contains the string "b".  If true, the string "OK" would be printed.

As it turns out, that string is not contained in the tuple, so the operation returns false and the "OK" string is not printed, as evidenced in Listing 3.
 

t2
('a', 'a')
length =  2

Listing 3

The true case

In the second case in Listing 2, a test is made to determine if the tuple contains the string "a".  If true, the tuple and its length are printed.

As you can see from Listing 3, this test returns true.  As a result, the name of the tuple, the tuple, and the length of the tuple are displayed.  (The tuple is displayed in boldface for emphasis.)

Pack the deeply-nested tuple

The code in Listing 4 packs the deeply-nested tuple by successively nesting the existing tuple into a new tuple.
 

t3 = 1, t2, 2
t4 = 3, t3, 4
t5 = 5, t4, 6

Listing 4

This code results in a tuple that is nested several levels deep as shown in Listing 6 later in the lesson.

Now print the deeply-nested tuple

As shown in Listing 4, the deeply-nested tuple is named t5.

The code in Listing 5 causes the name of the tuple, the tuple itself, and the length of the tuple to be displayed on the screen.
 

# print entire tuple
print "t5"
print t5
print "length = ",len(t5)

Listing 5

The output is shown in Listing 6 (with color added for clarity).
 

t5
(5, (3, (1, ('a', 'a'), 2), 4), 6)
length =  3

Listing 6

What is the length of the tuple?

It is very important to understand that even though you can count the following eight separate things in the tuple,

5 3 1 'a' 'a' 2 4 6

its length is only three (3), meaning that it only contains three items.

What are the available index values?

The three items contained in the tuple can be accessed using index values of 0, 1, and 2.

Everything that is highlighted in red in Listing 6 is a single item, which can be accessed using the index value of 1.

That item is a nested tuple, which also contains other nested tuples.

Using single square-bracket index notation

I discussed the use of single square-bracket indexing of tuples in a previous lesson.

The code in Listing 7 uses square-bracket index notation twice to access the item whose index value is 1.  Both instances are highlighted in boldface.
 

# now print using index values
print "t5[1]"
print t5[1]
print "length = ",len(t5[1])

Listing 7

In the first instance, the item is displayed on the screen.

In the second instance, the length of the item is determined and the length is displayed on the screen.

What does this code produce?

The output produced by this code is shown in Listing 8.
 

t5[1]
(3, (1, ('a', 'a'), 2), 4)
length =  3

Listing 8

The code in Listing 7 accesses and displays the tuple, which is nested at index value 1 in the tuple named t5.

What is the length of the tuple?

Again, note that the reported length of this tuple is 3 (see Listing 8), even though you can count six different things in the tuple.

As before, I used red to highlight the item at index value 1 in Listing 8.

The highlighted material is another tuple nested in this tuple.  The nested tuple contains even another nested tuple.

Using multiple square-bracket index notation

Now we have arrived at the primary purpose of this lesson, which is to teach you how to use multiple square-bracket notation for indexing nested tuples.

The code in Listing 9 illustrates how this is done.  I used color to highlight two instances in the code where multiple square-bracket indexing is used.
 

print "t5[1][1]"
print t5[1][1]
print "length = ",len(t5[1][1])

Listing 9

The first instance reads as follows:

print t5[1][1]

What does this mean?

You might interpret the above statement as follows:

Step 1
First extract the item at index value 1 from the tuple named t5.  This is indicated by the green portion of the above statement.

Step 2
Having extracted that item (which in this case is another nested tuple) extract the item from that tuple whose index value is also 1.  This is indicated by the violet portion of the above code.

Step 3
Having extracted that item (which in this case is another nested tuple), print it on the screen.

Play it again Sam!

A similar indexing operation is used in Listing 9 to determine the length of the extracted tuple (shown below with color added as above).

len(t5[1][1])

What is the length?

The output produced by the code in Listing 9 is shown in Listing 10.  As you can see, the length is 3 items.
 

t5[1][1]
(1, ('a', 'a'), 2)
length =  3

Listing 10

Just another tuple

As mentioned above, the extracted item shown in Listing 10 is another tuple with a length of 3.

The item at index value 1 of the extracted tuple, which I have highlighted using boldface in Listing 10, is another nested tuple.

Triple square brackets

That tuple can be extracted using three sets of square brackets as illustrated by the code in Listing 11.
 

print "t5[1][1][1]"
print t5[1][1][1]
print "length = ",\
               len(t5[1][1][1])

Listing 11

And the output is...

Listing 12 shows the output produced by the code in Listing 11.
 

t5[1][1][1]
('a', 'a')
length =  2

Listing 12

In this case, the extracted item is another tuple, with a length of 2.

Not just another pretty tuple

However, it doesn't contain another nested tuple.  Instead, it contains two strings.

Either of the items in this extracted tuple can be accessed using four sets of square brackets as illustrated by the code in Listing 13.
 

print "t5[1][1][1][1]"
print t5[1][1][1][1]
print "length = ",\
             len(t5[1][1][1][1])

Listing 13

The output produced by the code in Listing 13 is shown in Listing 14.
 

t5[1][1][1][1]
a
length =  1

Listing 14

Finally, the end of the nesting

At this point, we have worked our way down inside the nested structure to extract an item from the innermost nested tuple.

In this case, the item that we extract is not a tuple.  Rather, it is a string with a length of 1 and a value of "a" as shown in Listing 14.

Does it look familiar?

This is the value that was packed into the original tuple in Listing 1 before the nesting operation began.

Summary

The primary purpose of this lesson has been to teach you how to use multiple square-bracket notation for indexing nested tuples.  In addition, I have illustrated several other concepts including:
  • The repeat operator.
  • The membership operation.
  • Packing a deeply-nested tuple.
  • Printing a deeply-nested tuple.
  • Obtaining the length of a nested tuple.

What's Next?

Upcoming lessons will show you how to:
  • Slice nested tuples.
  • Modify values stored in an object referred to by an item in a tuple.

Review

1.  Write a Python script that illustrates the use of the repeat operator with tuples.

Ans:  See Listing 16.
 

# File Tuple20.py
# Rev 08/02/00
# Copyright 2000, R. G. Baldwin
# Illustrates the repeat
#  operator with tuples
#-------------------------------
t1 = "a",
t2 = t1*2
print t2

Listing 16

2.  Write a Python script that illustrates the use of the membership operator with tuples.

Ans:  See Listing 17.
 

# File Tuple21.py
# Rev 08/02/00
# Copyright 2000, R. G. Baldwin
# Illustrates the membership
#  operator with tuples
#-------------------------------
t1 = "a",
t2 = t1*2
print t2

if("a" in t2):
  print "Contains a"
if("b" in t2):
  print "Contains b"


Listing 17

3.  Write a Python script that illustrates the use of multiple square-bracket indexing to access and display an item in a nested tuple.

Ans:  See Listing 18.
 

# File Tuple22.py
# Rev 08/02/00
# Copyright 2000, R. G. Baldwin
# Illustrates the use of 
#  multiple square-bracket 
#  indexing
#-------------------------------
t1 =(1,(4,(7,8,9),6),3)
print t1[1][1][2]


Listing 18

4.  What is the length of the following tuple?

(1,(4,(7,8,9),6),3,10,11)

Ans:  The length is 5.  See Listing 19.
 

# File Tuple23.py
# Rev 08/02/00
# Copyright 2000, R. G. Baldwin
# Illustrates the length of a
#  nested tuple
#-------------------------------
t1 =(1,(4,(7,8,9),6),3,10,11)
print len(t1)


Listing 19

Listing of Sample Program

A complete listing of the program is shown in Listing 15.
 
# File Tuple05.py
# Rev 08/02/00
# Copyright 2000, R. G. Baldwin
# Illustrates indexing nested 
#  tuples
#
#-------------------------------
t1 = "a",
t2 = t1*2
if ("b" in t2)
  print "OK"
if ("a" in t2):
  print "t2"
  print t2
  print "length = ",len(t2)

t3 = 1,t2,2
t4 = 3,t3,4
t5 = 5,t4,6

# print entire tuple
print "t5"
print t5
print "length = ",len(t5)

# now print using index values
print "t5[1]"
print t5[1]
print "length = ",len(t5[1])

print "t5[1][1]"
print t5[1][1]
print "length = ",len(t5[1][1])

print "t5[1][1][1]"
print t5[1][1][1]
print "length = ",\
                len(t5[1][1][1])

print "t5[1][1][1][1]"
print t5[1][1][1][1]
print "length = ",\
             len(t5[1][1][1][1])

Listing 15



Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel