0% found this document useful (0 votes)
9 views25 pages

Touple

Uploaded by

Ankit Das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views25 pages

Touple

Uploaded by

Ankit Das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Tuple

Unit Structure
Objectives
Tuples
Accessing values in Tuples
Tuple Assignment
Tuples as return values
Variable-length argument tuples
Basic tuples operations
Concatenation
Repetition
In Operator
Iteration
Built-in Tuple Functions
OBJECTIVES:
1. To understand when to use a dictionary.
2. To study how a dictionary allows us to characterize attributes with keys and
values
3. To learn how to read a value from a dictionary
4. To study how in python to assign a key-value pair to a dictionary
5. To understand how tuples returns values

TUPLES:
A tuple in the Python is similar to the list. The difference between the two is that
we cannot change the element of the tuple once it is assigned to whereas we can
change the elements of a list

The reasons for having immutable types apply to tuples: copy efficiency: rather
than copying an immutable object, you can alias it (bind a variable to a
reference) ... interning: you need to store at most of one copy of any immutable
value. There’s no any need to synchronize access to immutable objects in
concurrent code.
Creating a Tuple:
A tuple is created by the placing all the elements inside parentheses '()',
separated by commas. The parentheses are the optional and however, it is a good
practice to use them.

A tuple can have any number of the items and they may be a different types
(integer, float, list, string, etc.).

Example:
Program:
# Different types of tuples
# Empty tuple
tuple = ()
print(tuple)
# Tuple having integers
tuple = (1, 2, 3)
print(tuple)
# tuple with mixed datatypes
tuple = (1, "code", 3.4)
print(tuple)
# nested tuple
tuple = ("color ", [6, 4, 2], (1, 2, 3))
print(tuple)

Output:
()
(1, 2, 3)
(1, 'code', 3.4)
('color ', [6, 4, 2], (1, 2, 3))
A tuple can also be created without using parentheses. This is known as tuple
packing.
Program:
tuple = 3, 2.6, "color"
print(tuple)
# tuple unpacking is also possible
a, b, c = tuple
print(a) # 3
print(b) # 2.6
print(c) # dog

Output:
(3, 2.6, 'color')
3
2.6
color
ACCESSING VALUES IN TUPLES:
There are various ways in which we can access the elements of a tuple.

1. Indexing:
We can use the index operator [] to access an item in a tuple, where the index
starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an
index outside of the tuple index range(6,7,... in this example) will raise an
IndexError.

The index must be an integer, so we cannot use float or other types. This will
result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.

# Accessing tuple elements using indexing


tuple = ('a','b','c','d','e','f')
print(tuple[0]) # 'a'
print(tuple[5]) # 'f'
# IndexError: list index out of range
# print(tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# tuple[2.0]
# nested tuple Output:
tuple = ("color", [6, 4, 2], (1, 2, 3)) a
# nested index f
o
print(tuple[0][3]) # 'o' 4
print(tuple[1][1]) # 4
2. Negative Indexing:
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.

Example:
# Negative indexing for accessing tuple elements
tuple = ('a','b','c','d','e','f')
# Output: 'f'
print(tuple[-1])
# Output: 'a'
print(tuple[-6])

Output:
f
a
3. Slicing:
We can access the range of items from the tuple by using the slicing operator
colon:
Example:
# Accessing tuple elements using slicing
tuple = ('a','b','c','d','e','f','g','h','i')
# elements 2nd to 4th
# Output: ('b', 'c', 'd')
print(tuple[1:4])
# elements beginning to 2nd
# Output: ('a', 'b')
print(tuple[:-7])
# elements 8th to end
# Output: ('h', 'i')
print(tuple[7:])
# elements beginning to end
# Output: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
print(tuple[:])

Output:
('b', 'c', 'd')
('a', 'b')
('h', 'i')
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
TUPLES AS RETURN VALUES:
Functions can return tuples as return values. Now we often want to know some
batsman’s highest and lowest score or we want to know to find the mean and the
standard deviation, or we want to know the year, the month, and the day, or if
we’re doing some ecological modeling we may want to know the number of
rabbits and the number of wolves on an island at a given time. In each case, a
function (which can only return a single value), can create a single tuple holding
multiple elements.

For example, we could write a function that returns both the area and the
circumference of a circle of radius.

Example:
def cirlce_info(r):
#Return (circumference, area) of a circle of radius r
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(cirlce_info(10))
Output:
(62.8318, 314.159)

CONCATENATION:
Now, we will learn 2 different ways to concatenate or join tuples in the python
language with code example. We will use ‘+” operator and a built-in sum()
function to concatenate or join tuples in python.
How to concatenate tuples into single/nested Tuples using sum():
Sum() to concatenate tuples into a single tuple:

In our first example, we will use the sum() function to concatenate two tuples
and result in a single tuple.Let us jump to example:

tupleint= (1,2,3,4,5,6)
langtuple = ('C#','C++','Python','Go')
#concatenate the tuple
tuples_concatenate = sum((tupleint, langtuple), ())
print('concatenate of tuples \n =',tuples_concatenate)

Output:
concatenate of tuples
= (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go')

Sum() to concatenate tuple into a nested tuple:


Now let us understand how we can sum tuples to make a nested tuple.In this
program we will use two tuples which are nested tuples, please note the ‘,’ at the
end of each tuples tupleint and langtuple.

let us understand example:


tupleint= (1,2,3,4,5,6),
langtuple = ('C#','C++','Python','Go'),
#concatenate the tuple
tuples_concatenate = sum((tupleint, langtuple), ())
print('concatenate of tuples \n =',tuples_concatenate)

Output:
concatenate of tuples
= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))

Concatenate tuple Using ‘+’ operator:


‘+’ operator to concatenate two tuples into a single tuple:

In our first example, we will use the “+” operator to concatenate two tuples and
result in a single tuple.In this example we have two tuple tupleint and
langtuple,We are the concatenating these tuples into the single tuple as we can
see in output.
tupleint= (1,2,3,4,5,6)
langtuple = ('C#','C++','Python','Go')
#concatenate the tuple
tuples_concatenate = tupleint+langtuple
print('concatenate of tuples \n =',tuples_concatenate)

Output:
concatenate of tuples
= (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go')

‘+’ operator with a comma(,) to concatenate tuples into nested Tuples:

This example, we have the two tuple tuple int and lang tuple. Now We are using
the comma(,) end of the each tuple to the concatenate them into a nested tuple.
We are concatenating these tuples into a nested tuple as we can see in the
resulting output.
# comma(,) after tuple to concatenate nested tuple
tupleint= (1,2,3,4,5,6),
langtuple = ('C#','C++','Python','Go'),
#concatenate the tuple into nested tuple
tuples_concatenate = tupleint+langtuple
print('concatenate of tuples \n =',tuples_concatenate)

Output:
concatenate of tuples
= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))
REPETITION:
Now, we are going to explain how to use Python tuple repetition operator with
basic syntax and many examples for better understanding.
Python tuple repetition operator (*) is used to the repeat a tuple, number of times
which is given by the integer value and create a new tuple values.

Syntax:
<tuple_variable_name1> * N
N * <tuple_variable_name1>

Input Parameters:
tuple_variable_name1 : The tuples that we want to be repeated.
N : where is the number of times that we want that tuple to be repeated
ex: 1,2,3,……..n
Example:
data=(1,2,3,'a','b')
# tuple after repetition
print('New tuple:', data* 2)

Output:
New tuple: (1, 2, 3, 'a', 'b', 1, 2, 3, 'a', 'b')

In the above Example, using repetition operator (*), we have repeated ‘data’
tuple variable 2 times by ‘data* 2’ in print statement and created new tuple as [1,
2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’, ‘b’].
IN OPERATOR:
The Python in operator lets you loop through all to the members of the
collection and check if there's a member in the tuple that's equal to the given
item.

Example:
my_tuple = (5, 1, 8, 3, 7)
print(8 in my_tuple)
print(0 in my_tuple)

Output:
True
False
It can also be used to check the presence of a sequence or substring against
string.

Example:
my_str = "This is a sample string"
print("sample" in my_str)

Output:
True

It can be uses in the many of other places and how it works in the those
scenarios of varies a lot. This is the how in works in tuples. It start the
comparing references of the objects from the first one till it either finds that the
object in the tuple or reaches in the end of the tuple.
ITERATION:
There are many ways to iterate through the tuple object. For statement in
Python has a variant which traverses a tuple till it is exhausted. It is
equivalent to for each statement in Java.
Its syntax is –
for var in tuple:
stmt1
stmt2

Example:
T = (10,20,30,40,50)
for var in T: Output:
0 10
print (T.index(var),var)
1 20
2 30
3 40
4 50
BUILT-IN TUPLE FUNCTIONS:
Tuples support the following build-in functions:

Comparison:
If the elements are of the same type, python performs the comparison and
returns the result. If elements are different types, it checks whether they are
numbers.

If numbers, perform comparison.

If either the element is an number, then the other element is a returned.

Otherwise, types are sorted alphabetically.

If we reached to the end of one of the lists, the longer list is a "larger." If both are
list are same it returns 0.
tuple1 = ('a', 'b', 'c', 'd', 'e')
tuple2 = ('1','2','3')
tuple3 = ('a', 'b', 'c', 'd', 'e')
print(tuple1==tuple2)
#Out: 1
print(tuple2== tuple1)
#Out: -1
print(tuple1==tuple3)
#Out: 0

Output:
False
False
True
END

You might also like