Python Programming – Creation, Initialization and Accessing The Elements In A Tuple

You can learn about Tuples in Python Programs with Outputs helped you to understand the language better.

Python Programming – Creation, Initialization and Accessing The Elements In A Tuple

To create a tuple with zero elements, use only a pair of parentheses “( )”. For a tuple with one element, use a trailing comma. For a tuple with two or more elements, use a comma between elements. No ending comma is needed here.

Tuple Creation

Creating a tuple means placing different comma- separated values within parentheses. However, the parentheses are optional. Also, the elements of a tuple can be of any valid Python data types ranging from numbers, strings, lists, etc. For example:
>>> tup1 = (‘C++’, ‘Python’, 1997, 2013)
>>> tup2 = (1, 2, 3, 4, 5 )
>>> tup3 = “a”, “b”, “c”, “d”
Once a tuple is created, you cannot change its values. Tuples are unchangeable.

  • You cannot delete or add elements in a tuple, once it is created.

The empty tuple is formed with a pair of parentheses containing nothing. For example:

# Demo of zero-element/empty tuple
tup4 = ( )
>>> len ( tup4 )
0

you may get the length of a tuple by using the len function. simply, provide a tuple name in the parentheses after len keyword.

To write a tuple containing a single value you have to include a trailing comma, even though there is only one value. For example:

# Demo of one-element tuple
tup5 = ( 20 , )
>>> len ( tup5 )
1

Take another example to understand it in better way:

>>> t3 = ( 1 , )
>>> t3
( 1 , )
>>> type ( t3 )
<type ‘tuple’>

It is important to note that declaring a tuple consisting a single element requires a comma after the first element. If you miss out the comma, t3 would become an integer because 1 itself is an integer.

>>> t3 = (1)
>>> type(t3)
<type ‘int’>
# Two-element tuple
tup6 = (“one”, “two”)
>>> len(tup6)
2
# Tuple of numbers
>>> tuple1 = ( 0, 1, 2, 3 )
>>> print( “A tuple of numbers:”,tuple1 )
A tuple of numbers: ( 0, 1, 2, 3 )
>>>

The tuple in Python is immutable. An immutable object cannot be changed. Once created, it always has the same values. Trying to make an item assignment in a tuple will display the following error:

>>> tup = (‘a’, ‘b’, ‘d’, ‘d’)
>>> tup[2] = ‘c’ # This causes an error
Traceback (most recent call last):
File “<pyshe11#14>”, line 1, in <module>
tup[2] = ‘c’ # This causes an error
TypeError: ‘tuple’ object does not support item assignment

  • To declare a tuple, you must type a list of items sep¬arated by commas, inside parentheses. Then assign it to a variable. For example, marks=(97,88,92)
# Creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = (‘Hello’, ‘Python’)
tuple3 = (tuple1, tuple2)
print(tuple3)>>>
((0, 1, 2, 3), (‘Hello’, ‘Python’))
>>>

Let’s Try

tup_eg = (11,12,13,14,15)
print (“Total number of elements in
tuple = “, len(tup_eg))
# Create tuples (one with brackets, one without) and print them
weekdays = (“Mon”, “Tues”, “Wed”, “Thur”, “Fri”)
weekends = “Sat”, “Sun”# Print the tuples
print(weekdays)
print(weekends)

Tuple Assignment

You can assign all the elements in a tuple using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, which makes it useful for swapping values.
To swap the values of two variables with conventional assignment statements, you have to use a temporary variable. For example, to swap x and y:
>>> temp = x
>>> x = y
>>> y = temp
In Python, you can assign all the elements in a tuple using a single assignment statement:
>>> x, y = y, x
The left side is tuple variables, and the right side is tuple values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before allocating any assignment.
The number of variables on the left and the number of values on the right has to be the same:
>>> x, y = 1, 2, 3
ValueError: too many values to unpack

Accessing Elements in Tuples

Tuple items can be accessed by referring to the index number, inside square brackets. Like string indices, tuple indices begin at 0. Accessed items can be either single elements or in groups, known as slices. Subsets can be accessed with the slice operator ( [ ] and [:] ) as in strings. The slice notation in Python uses a colon. On the left side of the colon, you have the starting index. If no starting index is present, the program uses 0. And on the right side of the colon, you have the ending index. If no ending index is present, the last possible index is used. For example,
tup1 = (‘Mona’, ‘Monty’, 1997, 2003)
>>> tup1[0]
‘Mona’
>>> tup1[1]
‘Monty’
Note: Indexes start with 0 that is why you use 0 to access the first element of the tuple, 1 to access the second element, and so on.

  • When using positive indices, you traverse the list from the left.

Python allows negative indexing for its sequences. Similar to list and strings you can use negative indexes to access the tuple elements from the end. If you want to access value 2003, you can write either tupl[-l] or tup1 [3]. The index of -1 refers to the last item, -2 to the second last item, and so on.
>>> tup1[-1] # Negative index
2003
>>> tup1[3] # Positive index
2003

  • Unlike positive indexing, negative indexing begins traversing from the right.

To access values in tuple, use the square brackets along with the index:

>>> t1 = (1, “abc”, 7.0)
>>> t1 [0] # accessing first element
1
>>> t1 [1]
‘ abc’
>>> t1 [2]
7.0
>>> t1[3]
Traceback (most recent call last):
File “<pyshell#9>”, line 1, in <module> t1 [3]
IndexError: tuple index out of range This error occurs when you mention the index which is not in the range. For example, if a tuple has 3 elements and you try to access the 4th element then this error would occur.
You can use negative indexes to access the tuple elements from the end; -1 to access the last element, -2 to access second last and so on as shown in the example below:
>>> t1[-1]
7.0
>>> t1 [-2]
‘ abc’
>>> t1[-3]
1
Likewise, nested tuples are accessed using nested indexing, as shown in the example below:

# Accessing Nested Tuple Items
Tuple = ((1, 2, 3), [4, 5, 6], ‘Hello’)
print(Tuple[0][0])
print(Tuple[1][0])
print(Tuple[2][0])
print(Tuple[2][4])
>>>
1
4
H
O
>>>

Example
Demo of accessing nested tuple.

# Accessing nested tuples
Tuple = ([7,4,3], “Raj”, (10, 11, 12))
print(Tuple[0][0])
print(Tuple[0][1])
print(Tuple[0] [2])print(Tuple[2][0])
print(Tuple[2][1])
print(Tuple[2][2])
RUN
>>>
7
4
3
R
a
j
10
11
12
>>>

Slices are treated as boundaries, and the result will contain all the elements between these boundaries. So, a tuple having 5 elements will have indices from 0 to 4. Trying to access an element outside of the tuple will raise an IndexError.
>>> tup2 = (1, 2, 3, 4, 5)
>>> tup2[1:5]
(2, 3, 4, 5)
>>> tup2[3:7]
(4, 5)
>>> tup2[8]
Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module> tup2 [8]
IndexError: tuple index out of range The index must be an integer; so you cannot use float or other types. This will result in TypeError.

  • A slice is created using the subscript notation, [ ] with colons between starting and ending index.

Let’s Try

Write the output for the following Python code:

tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
>>> fruits = “apple” , “orange” , “banana” , “berry” , “mango”
>>> fruits [0]
>>> t1 = (1, “abc” , 3 . 0 )
>>> t1
>>> type (t1)

Example
Write a program that uses tuple slices.

values = (1, 3, 5, 7, 9, 11, 13)
# Copy the tuple
print(values[:])
# Copy all values at index 1 or more
print(values[1:])
# copy one value, starting at first
print (value [:1] )# copy values from index 2 to 4
print (value [2:4])RUN
>>>
( 1, 3, 5, 7, 9, 11, 13)
(3, 5, 7, 9, 11, 13)
(1,)
(5, 7)
>>>

Membership Test in Tuples

Membership operators “in” and “not in” checks whether the given element is contained in the tuple or not. For example:
>>> 4 in (2, 4, 6, 8)
True
>>> 5 in (2, 4, 6, 8)
False
>>> 4 not in (2, 4, 6, 8)
False
>>> 5 not in (2, 4, 6, 8)
True
>>> ‘a’ in tuple(“python”)
False
>>> ‘a’ not in tuple(“python”)
True
Identity operator “is” returns true, if the variables on either side of the operator point to the same memory location, and false otherwise. For example,

Example
Demo of identity operator.

a = ‘ Janak puri’
b = ‘ Dwarka’
c = ‘ Dwarka’
if a is b:
print (‘a is b’)
else:
print (‘a is not b’)
if b is c:
print (‘b is c’)
else:
print (‘b is not c’)RUN
>>>
a is not b
b is c
>>>

Identity operator “is not” returns true if both the operand point to different memory locations. It is the opposite of the “is” operator.

Let’s Try

Write the output for the following python code:

>>> tuple = ( ‘p’ , ‘y’ , ‘t’ , ‘h’ , ‘c’ , ‘n’ )
>>> for item in tuple:
print (“Item:”, item)

Leave a Reply

Your email address will not be published. Required fields are marked *