How to Deal With Nested Tuples in Python
In Python programming, tuples are one of seven built-in sequence types. Similar in appearance to a list, a comma separates individual elements – even if the tuple includes only one element — and in the case of nested tuples, parentheses identify nesting levels. Unlike a list, however, the elements in a tuple are not changeable, making tuples a good choice for constant data – or data that once entered will not undergo further editing. Understanding the concept of nesting is important, as dealing with this type of tuple can be tricky, especially when nesting involves multiple layers.
Instructions
-
-
1
Create a nested tuple by combining – or “packing” - two or more single level tuples. Define single tuples and then write a Python statement to create a nested tuple. Enclosing a single or nested tuple inside parentheses is not a requirement, but parentheses can help organize and make your data easier to read:
t1 = (1, 2, 3)
t2 = (“and”, “or”)t3 = (t1, “X”, “Y”, t2, “Z”)
(Reference 3-section 3-#1) -
2
Get the length of a nested tuple to help you understand how Python counts and indexes the items in a nested tuple. Counting begins with “0” so the Python statement “print “The length of t3 is: print len(t3)” will appear on your computer screen as: The length of the t3 is: 4.
-
-
3
Print the nested tuple so individual elements display on your screen in the same way you originally entered them. The statement “print t3[:]” will display on your computer screen as ((1, 2,3), “X”, “Y”, (“and”, “or”), “Z”).
-
4
Slice the nested tuple so only specific contents appear on your computer screen. The syntax for slicing a nested tuple starts by identifying the name of the top-level tuple – the nested tuple – followed by starting and ending index numbers in brackets. The statement “print t3[2:4]” will result in index numbers 2 through 4 appearing on your screen: (“Y”, (“and”, “or), “Z”).
-
5
Extract individual elements from within a tuple. A statement that reads “print t3 [1] [0:1]” will display the first two items in the first tuple in the nested group: (1, 2).
-
1
References
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images