Introduction To Tuples: #Creates An Empty Tuple
Introduction To Tuples: #Creates An Empty Tuple
Introduction To Tuples: #Creates An Empty Tuple
Example:
T1 = () #Creates an Empty Tuple
T2 = (12,34,56,90) #Create Tuple with 4
elements
T3 = ('a','b','c','d','e') #Create Tuple of 5
characters
T4 = 1,2,3,4,5 #Create Tuple without parenthesis
Built-in functions for Tuples
Built-in Meaning
Functions
len() Returns the number of elements in the tuple.
H E L L O
a[-5] a[-4] a[-3] a[-2] a[-1]
>>> a[4]
'O'
>>> a[-4]
'E'
Tuples are immutable
Unlike Lists we cannot change the elements of
tuples.
>>> t=(['A','B'],['C','D'])
>>> type(t)
<class 'tuple'>
>>> t[0]=['x','Y']
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
t[0]=['x','Y']
TypeError: 'tuple' object does not support item assignment
The + and * operator on Tuples
The + operator - The concatenation + operator is
used to join two tuples.
Example:
>>> a=('A','B')
>>> b=(1,2)
>>> a+b
('A', 'B', 1, 2)
>>> type(a+b)
<class 'tuple'>
The * operator – It is used to replicate the
elements of a tuple.
>>> t = (1,2,3)
>>> t *2
(1, 2, 3, 1, 2, 3)
Passing Variable Length Arguments to a
Tuple
>>> create_tup(1,2,3,4)
(1, 2, 3, 4)
>>> create_tup('a','b')
('a', 'b')
Sorting elements of Tuple
Tuple does not support any sort method to sort the
contents of Tuple.
Example:
>>> t=(76,45,23,11) #Tuple
>>> t=list(t) #Converted Tuple to a List
>>> t.sort() #Sort method of List
>>> tuple(t) #Converting List to tuple
(11, 23, 45, 76)
Zip() function
The zip() is one of the built in python functions.
Example:
>>> t1=('Z','Y',',X')
>>> t2 =(26, 25, 24)
>>> zip(t1,t2)
[('Z', 26), ('Y', 25), (',X', 24)]
Introduction to sets
Set is an unordered collection of elements.
It is a collection of unique elements.
Duplication of elements is not allowed.
Sets are mutable so we can easily add or remove
elements.
A programmer can create a set by enclosing the elements
inside a pair of curly braces i.e. {}.
The elements within the set are separated by commas.
The set can be created by the in built set() function.
Example:
>>> s2 = {1,2,3,4,5}
>>> s2
{1, 2, 3, 4, 5}
>>> type(s2)
<class 'set'>
Methods of Set Class
Function Meaning
s.add(x) Add element x to existing set s.
Example:
>>> A = {1,2,3,4}
>>> B = {2,5,6,7,9}
>>> A.difference(B)
{1, 3, 2}
Example:
>>> A = {1,2,3,4}
>>> B = {2,5,6,7,9}
>>> A.symmetric_difference(B)
{1,3,4,5,6,7,9}
Output: