Python Unit-3
Python Unit-3
Python Unit-3
UNIT-3
Sequence
• A sequence is a datatype that represents
a group of elements.
• The purpose of any sequence is to store
and process group elements.
• In python, strings, lists, tuples and
dictionaries are very important sequence
datatypes.
List
• A list is similar to an array that consists of a
group of elements or items.
• The Difference is …………….
• An array can store only one type of elements
whereas a list can store different types of
elements.
• To create a List as putting different comma-
separated values between square brackets [ ].
List
• Example:
Student=[556, “hello", 84, 96, 84, 75, 84]
• To Create empty List without any elements by
simply writing empty square brackets as:
Student=[ ]
List
• Accessing values in List:
– use the square brackets for slicing along with the
index or indices to obtain value available at that
index.
negative Indexing
Positive Indexing
Student
List
Program:
Output:
student = [556, “Mothi”, 84, 96, 84, 75, 84 ]
print student [556, "Mothi", 84, 96, 84, 75, 84]
print student[0] Mothi
print student[0:2] [556, "MOTHI"]
print student[2: ]
[84, 96, 84, 75, 84]
[556, "MOTHI", 84]
print student[ :3]
[556, "MOTHI", 84, 96, 84, 75, 84]
print student[ : ]
84
print student[-1]
[84, 75, 84, 96, 84, "MOTHI"]
print student[-1:-7:-1]
range() function
• range() function used to print list of integer
values.
• Syntax:
– range(start, end [, step])
range() function
• Example:
List
• Creating List using range() function:
numbers=range(0,9)
print numbers #[0,1,2,3,4,5,6,7,8]
numbers=range(0,9,2)
print numbers #[0,2,4,6,8]
List
• Looping over List:
numbers=[1,2,3,4,5]
for i in numbers:
print i,
Output:
1 2 3 4 5
List
• Updating and Deleting List:
– Lists are mutable.
– It means we can modify the contents of a
list.
– We can append, update or delete the
elements of a list depending upon our
requirements.
List
Program: Output:
a = [4, 7, 6, 8, 9]
print a [4, 7, 6, 8, 9]
a[2] = 45
print a [4, 7, 45, 8, 9]
a[2:5] = 10, 11, 12
print a [4, 7, 10, 11, 12]
List
Program: Output:
a = [4, 7, 6, 8, 9]
print a [4, 7, 6, 8, 9]
del a[3]
print a [4, 7, 6, 9]
List
• Concatenation of Two lists
– We can simply use ‘+’ operator on two lists to join
them.
Program: Output:
a = [4, 7, 6, 8, 9]
b = [1, 2, 3]
print a+b [4, 7, 6, 8, 9, 1, 2, 3]
List
• Repetition of Two lists
– We can repeat the elements of a list ‘n’ number of
times using ‘ * ’ operator.
Program: Output:
a = [4, 7, 6, 8, 9]
[4, 7, 6, 8, 4, 7, 6, 8]
print a*2
List
• Membership in lists
– We can check if an element is a member of a list
by using ‘in’ and ‘not in’ operator.
Program:
a = [4, 7, 6, 8, 9] Output:
x=7
print x in a True
y = 10
print y not in a True
List
• Aliasing lists
– Giving a new name to an existing list is called ‘aliasing’.
– To provide a new name to this list, we can simply use
assignment operator (=).
y
Before Modifications
y
After Modifications
List
Program:
a = [10, 20, 30, 40, 50, 60]Output:
x=a
print a [10, 20, 30, 40, 50, 60]
print x [10, 20, 30, 40, 50, 60]
a[1]= 90
print a [10, 90, 30, 40, 50, 60]
print x [10, 90, 30, 40, 50, 60]
List
• Cloning lists
– Obtaining exact copy of an existing object
(or list) is called ‘cloning’.
– To Clone a list, we can take help of the
slicing operation [:].
List
Before Modifications
After Modifications
List
Program:
a = [10, 20, 30, 40, 50, 60]Output:
x = a[ : ]
print a [10, 20, 30, 40, 50, 60]
print x [10, 20, 30, 40, 50, 60]
a[1]= 90
print a [10, 90, 30, 40, 50, 60]
print x [10, 20, 30, 40, 50, 60]
List
Method Description
lst.index(x) Returns the first occurrence of x in the list.
lst.append(x) Appends x at the end of the list.
lst.insert(i,x) Inserts x to the list in the position specified by i.
lst.copy() Copies all the list elements into a new list and returns it.
Program: Output:
a = [[1, 2],[3,4],[5,6]]
print a[1] [1,2]
print a[2][1] 6
for i in a[2]:
print i, 5 6
List
• List Comprehensions:
– List comprehensions represent creation of new
lists from an iterable object that satisfy a given
condition.
squares=[ ]
for i in range(1,11):
squares.append(i**2)
Can be rewritten as………..
A=[x**2 for x in range(1,11)]
Tuple
• A Tuple is a python sequence which stores a group
of elements or items.
• Tuples are similar to lists but the main difference
is tuples are immutable whereas lists are mutable.
• Once we create a tuple we cannot modify its
elements.
• Tuples are generally used to store data which
should not be modified and retrieve that data on
demand.
Tuple
• Creating a tuple by writing elements
separated by commas inside parentheses ( ).
– tup = (10, 556, 22.3, “Mayank”)
• To create a tuple with only one element, we
can, mention that element in parenthesis and
after that a comma is needed.
Tuple
• Accessing values in Tuple:
– Accessing the elements from a tuple can be done using
indexing or slicing.
tup = (50,60,70,80,90)
print tup[0] # 50
print tup[1:4] # (60,70,80)
print tup[-1] # 90
print tup[-1:-4:-1]# (90,80,70)
print tup[-4:-1] # (60,70,80)
Tuple
• Updating and deleting in Tuple:
– Tuples are immutable which means you cannot
update, change or delete the values of tuple
elements.
Tuple
Tuple
Operation Description
len(t) Return the length of tuple.
tup1+tup2 Concatenation of two tuples.
tup*n Repetition of tuple values in n number of times.
x in tup Return True if x is found in tuple otherwise returns False.
Program:
students=(("RAVI", "CSE", 92.00), ("RAMU", "ECE", 93.00),
("RAJA", "EEE", 87.00))
for i in students:
print i
Output:
("RAVI", "CSE", 92.00)
("RAMU", "ECE", 93.00)
("RAJA", "EEE", 87.00)
Set
• Set is another data structure supported by
python.
• Basically, sets are same as lists but with a
difference that sets are lists with no duplicate
entries.
• Technically a set is a mutable and an
unordered collection of items. This means that
we can easily add or remove items from it.
Set
• Creating a set:
– A set is created by placing all the elements
inside curly brackets { }.
s={1, 2.5, "abc" }
print s
Output:
set([1, 2.5, "abc" ])
Set
• Converting list into a set:
– A set can have any number of items and
they may be of different data types. set()
function is used to converting list into set.
s=set([1, 2.5, "abc"])
print s
Output:
set([1, 2.5, "abc" ])
Set
Operation Description
len(s) number of elements in set s (cardinality)
s.issubset(t)
(or) test whether every element in s is in t
s <= t
s.issuperset(t)
(or) test whether every element in t is in s
s >= t
s.union(t)
(or) new set with elements from both s and t
s|t
s.intersection(t)
(or) new set with elements common to s and t
s&t
s.copy() new set with a shallow copy of s
s.update(t) return set s with elements added from t
Dictionary
• A dictionary represents a group of elements
arranged in the form of key-value pairs. The
first element is considered as ‘key’ and the
immediate next element is taken as its ‘value’.
• The key and its value are separated by a colon
(:). All the key-value pairs in a dictionary are
inserted in curly braces { }.
Dictionary
• Program:
d= { 'Regd.No': 556, 'Name':'Mothi', 'Branch': 'CSE' }
print d['Regd.No'] # 556
print d['Name'] # Mothi
print d['Branch'] # CSE
Dictionary
• Program:
d={'Regd.No':556,'Name':'Mothi','Branch':'CSE'}
print d
d['Gender']="Male"
print d
Output:
{'Regd.No':556,'Name':'Mothi','Branch':'CSE'}
{'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi',
'Regd.No': 556}
Dictionary
Method Description
Removes the key ‘k’ and its value from‘d’ and returns the value. If
d.pop(k [,v] ) key is not found, then the value ‘v’ is returned. If key is not found
and ‘v’ is not mentioned then ‘KeyError’ is raised.
If key ‘k’ is found, its value is returned. If key is not found, then
d.setdefault(k [,v] ) the k, v pair is stored into the dictionary‘d’.