1
MODULE – III
2
SYLLABUS
CONTAINER DATA TYPES
Lists: Accessing List elements, List operations, List methods, List
comprehension; Tuples: Accessing Tuple elements, Tuple
operations, Tuple methods, Tuple comprehension, Conversion of List
comprehension to Tuple, Iterators and Iterables, zip() function.
Sets: Accessing Set elements, Set operations, Set functions, Set
comprehension; Dictionaries: Accessing Dictionary elements,
Dictionary operations, Dictionary Functions, Nested Dictionary,
Dictionary comprehension.
3
Introduction
• The most basic data structure in Python is the sequence.
• Each element of a sequence is assigned a number - its position or
index.
• The first index is zero, the second index is one, and so forth.
• Python has four built-in types of sequences.
• There are certain things you can do with all sequence types.
• These operations include indexing, slicing, adding, multiplying,
and checking for membership. In addition, Python has built-in
functions for finding the length of a sequence and for finding its
largest and smallest elements.
4
Lists
• Python offers a range of compound data types often referred to
as sequences.
• List is one of the most frequently used and very versatile data
types used in Python.
• A list in Python is used to store the sequence of various types of
data.
• Python lists are mutable type its mean we can modify its element
after it created.
• A list can be defined as a collection of values or items of
different types. The items in the list are separated with the
comma (,) and enclosed with the square brackets [ ].
5
How to create a list?
• In Python programming, a list is created by placing all the items
(elements) inside square brackets [ ], separated by commas.
• It can have any number of items and they may be of different
types (integer, float, string etc.).
• # empty list
• my_list = [ ]
• # list of integers
• my_list = [1, 2, 3]
• # list with mixed data types
• my_list = [1, "Hello", 3.4]
6
Nested list?
• A list can also have another list as an item. This is called a nested
list.
• # nested list
• my_list = ["mouse", [8, 4, 6], ['a']]
7
Characteristics of Lists
The list has the following characteristics:
• The lists are ordered.
• The element of the list can access by index.
• The lists are the mutable type.
• A list can store the number of various elements.
8
How to access elements from a list?
• We can use the index operator [] to access an item in a list.
• In Python, indices start at 0.
• So, a list having 6 elements will have an index from 0 to 5.
• Trying to access indexes other than these will raise an IndexError.
• The index must be an integer. We can't use float or other types,
this will result in TypeError.
9
How to access elements from a list?
10
How to access elements from a list?
print(List[-1])=5
print(List[-2])=4
print(List[-3])=3
print(list[-3:])= [3,4,5]
print(list[:-1]) =[0,1,2,3,4]
print(list[-3:-1]) =[3,4]
11
Python List Built-in functions
• Python List append()
Add a single element to the end of the list
• Python List clear()
Removes all Items from the List
• Python List copy()
returns a shallow copy of the list
• Python List count()
returns count of the element in the list
12
Python List Built-in functions
• Python List extend()
adds iterable elements to the end of the list
• Python List index()
returns the index of the element in the list
• Python List insert()
insert an element to the list
• Python List pop()
Removes element at the given index
13
Python List Built-in functions
• Python List remove()
Removes item from the list
• Python List reverse()
reverses the list
• Python List sort()
sorts elements of a list
14
Python List Operations
Operator Description Example
Repetition The repetition operator enables
the list elements to be repeated
multiple times.
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
L1*2 =
[1, 2, 3, 4, 1, 2, 3, 4]
Concatenation It concatenates the list mentioned
on either side of the operator.
l1+l2 =
[1, 2, 3, 4, 5, 6, 7, 8]
Membership It returns true if a particular item
exists in a particular list otherwise
false.
print(2 in l1)
prints True.
Iteration The for loop is used to iterate
over the list elements.
for i in l1:
print(i)
Output1 2 3 4
Length It is used to get the length of the
list
len(l1) = 4
15
List Comprehensions Python
• List comprehensions provide a concise way to create lists.
• Common applications are to make new lists where each
element is the result of some operations applied to each
member of another sequence or iterable, or to create a
subsequence of those elements that satisfy a certain
condition.
16
List Comprehensions Python
• create a list of squares can be done by following
>>> squares = [ ]
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
17
List Comprehensions Python
• Syntax
• list_variable = [x for x in iterable]
• list of squares can also be find using list comprehension as
follows
>>> squares = [x**2 for x in range(10)]
• A list comprehension consists of brackets containing an
expression followed by a for clause, then zero or more for or if
clauses.
• The result will be a new list resulting from evaluating the
expression in the context of the for and if clauses which follow
it.
18
Tuples in Python
• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
19
List vs Tuple
List Tuple
1 The literal syntax of list is shown by the
[ ].
The literal syntax of the tuple is
shown by the ().
2 The List is mutable. The tuple is immutable.
3 List iteration is slower and is time
consuming.
Tuple iteration is faster.
4
Lists consume more memory
Tuple consume less memory as
compared to the list
5 The list is used in the scenario in which
we need to store the simple
collections with no constraints where
the value of the items can be changed.
The tuple is used in the cases where
we need to store the read-only
collections i.e., the value of the
items cannot be changed. It can be
used as the key inside the
dictionary.
6 List provides many in-built methods. Tuples have less in-built methods.
20
Creating a Tuple
• A tuple is created by placing all the items (elements) inside
parentheses ( ), separated by commas.
• The parentheses are optional, however, it is a good practice to
use them.
• A tuple can have any number of items and they may be of
different types (integer, float, list, string, etc.).
21
• # Different types of tuples
• # Empty tuple
• my_tuple = ()
• print( my_tuple )
• # Tuple having integers
• my_tuple = (1, 2, 3)
• print( my_tuple )
• # tuple with mixed data types
• my_tuple = (1, "Hello", 3.4)
• print( my_tuple)
• # nested tuple
• my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
• print( my_tuple)
Creating a Tuple
22
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 will raise an
IndexError.
• The index must be an integer, so we cannot use float or other
types. This will result in TypeError.
How to access Tuple elements
23
How to access Tuple elements
24
Negative Indexing
How to access Tuple elements
• The tuple element can also access by using negative indexing.
• The index of -1 denotes the rightmost element and -2 to the
second last item and so on.
• Example
• Statement Output
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1]) 5
print(tuple1[-4]) 2
print(tuple1[-3:-1]) (3, 4)
print(tuple1[:-1]) (1, 2, 3, 4)
print(tuple1[-2:]) (4, 5)
25
The operators like concatenation (+), repetition (*), Membership (in) works in the
same way as they work with the list.
Basic Tuple operations
Operator Description Example
Repetition The repetition operator enables the
tuple elements to be repeated
multiple times.
T1= (1, 2, 3, 4, 5)
T2 = (6, 7, 8, 9)
T1*2 = (1, 2, 3, 4, 5, 1, 2,
3, 4, 5)
Concatenation It concatenates the tuple mentioned
on either side of the operator.
T1+T2 = (1, 2, 3, 4, 5, 6, 7,
8, 9)
Membership It returns true if a particular item
exists in the tuple otherwise false
print (2 in T1) prints True.
Iteration The for loop is used to iterate over
the tuple elements.
for i in T1:
print(i)Output1 2 3 4 5
Length It is used to get the length of the
tuple.
len(T1) = 5
26
Python Tuple built-in functions
SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns
true if tuple1 is greater than tuple2
otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the
tuple
4 min(tuple) It returns the minimum element of the
tuple.
5 tuple(seq) It converts the specified sequence to
the tuple.
27
Tuple Methods
Method Description
count() Returns the number of times a specified value occurs
in a tuple
index() Searches the tuple for a specified value and returns
the position of where it was found
28
Update Tuples
• Tuples are unchangeable, meaning that you cannot change,
add, or remove items once the tuple is created.
• Tuples are unchangeable or immutable.
29
Unpacking Tuples
• When we create a tuple, we normally assign values to it.
• This is called "packing" a tuple
Example
• Packing a tuple:
• fruits = ("apple", "banana", "cherry")
• But, in Python, we are also allowed to extract the values back
into variables. This is called "unpacking“.
• fruits = ("apple", "banana", "cherry")
• (green, yellow, red) = fruits
• print(green)
• print(yellow)
• print(red)
• Output: apple, yellow, red
30
Tuple comprehension
Tuple comprehension
Example :
T=(-1,2,-3,4,6)
T=tuple(i for i in T if i>0)
Output:
[2,4,6]
List comprehension
Example:
L=[-1,2,-3,4,6]
L2=[i for i in L if i>0]
Output:
[2,4,6]
31
Conversion of List comprehension to Tuple
Example
L=[1,2,3,4,5,6,7]
T=tuple([i for i in L])
Print(T)
Output:
(1,2,3,4,5,6,7)
32
Iterator
In Python, an iterator is an object which implements the iterator
protocol, which consist of the methods __iter__() and
__next__() .
• An iterator is an object representing a stream of data.
• It returns the data one element at a time.
• A Python iterator must support a method called __next__() that
takes no arguments and always returns the next element of the
stream.
• If there are no more elements in the stream, __next__() must
raise the StopIteration exception.
• Iterators don’t have to be finite. It’s perfectly reasonable to
write an iterator that produces an infinite stream of data.
33
Iterable
• In Python, Iterable is anything you can loop over with a for
loop.
• An object is called an iterable if u can get an iterator out of it.
• Calling iter() function on an iterable gives us an iterator.
• Calling next() function on iterator gives us the next element.
• If the iterator is exhausted(if it has no more elements), calling
next() raises StopIteration exception.
34
Iterable
35
Iterating through an Iterator
• We use the next() function to manually iterate through all the
items of an iterator.
• When we reach the end and there is no more data to be
returned, it will raise the StopIteration Exception.
# define a list
my_list = [4, 7, 0, 3]
# get an iterator using iter()
my_iter = iter(my_list)
# iterate through it using next()
# Output: 4
print(next(my_iter))
36
Iterating through an Iterator
# Output: 7
print(next(my_iter))
# next(obj) is same as
obj.__next__()
# Output: 0
print(my_iter.__next__())
# Output: 3
print(my_iter.__next__())
# This will raise error, no items left
next(my_iter)
37
Working of for loop for Iterators
for <var> in <iterable>:
<statement(s)>
Multi dimensional list
• A list represents a one-dimensional (1D), linear data structure. We can display a list’s
elements from beginning to end in a straight line; for example:
[9, 17, 88, 2, 17, 6, 45]
We can locate an element uniquely within the list via a single integer index, its offset from
the beginning of the list. In the example list above, element 88 is at index 2.
Some kinds of information are better represented two-dimensionally, in a rectangular array
of elements, also known as a matrix; for example,
100 14 8 22 71
0 243 68 1 30
90 21 7 67 112
115 200 70 150 8
How are 2D matrices used?
• Mathematicians can represent a system of equations in a matrix and use
techniques from linear algebra to solve the system.
• Computer scientists use 2D matrices to model the articulation of roboti
arms.
• Computer graphics programmers mathematically manipulate 2D matrices to
transform data in 3D space and project it onto a 2D screen giving users the
illusion of depth, motion, location.
• Many classic games such as chess, checkers, Go, and Scrabble involve a 2D
grid of board positions that naturally maps to a 2D matrix.
• A word search puzzle is a rectangular array of letters, and a maze is simply a
2D arrangement of adjoining rooms, some of which are connected and
others that are not.

tupple.pptx

  • 1.
  • 2.
    2 SYLLABUS CONTAINER DATA TYPES Lists:Accessing List elements, List operations, List methods, List comprehension; Tuples: Accessing Tuple elements, Tuple operations, Tuple methods, Tuple comprehension, Conversion of List comprehension to Tuple, Iterators and Iterables, zip() function. Sets: Accessing Set elements, Set operations, Set functions, Set comprehension; Dictionaries: Accessing Dictionary elements, Dictionary operations, Dictionary Functions, Nested Dictionary, Dictionary comprehension.
  • 3.
    3 Introduction • The mostbasic data structure in Python is the sequence. • Each element of a sequence is assigned a number - its position or index. • The first index is zero, the second index is one, and so forth. • Python has four built-in types of sequences. • There are certain things you can do with all sequence types. • These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.
  • 4.
    4 Lists • Python offersa range of compound data types often referred to as sequences. • List is one of the most frequently used and very versatile data types used in Python. • A list in Python is used to store the sequence of various types of data. • Python lists are mutable type its mean we can modify its element after it created. • A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [ ].
  • 5.
    5 How to createa list? • In Python programming, a list is created by placing all the items (elements) inside square brackets [ ], separated by commas. • It can have any number of items and they may be of different types (integer, float, string etc.). • # empty list • my_list = [ ] • # list of integers • my_list = [1, 2, 3] • # list with mixed data types • my_list = [1, "Hello", 3.4]
  • 6.
    6 Nested list? • Alist can also have another list as an item. This is called a nested list. • # nested list • my_list = ["mouse", [8, 4, 6], ['a']]
  • 7.
    7 Characteristics of Lists Thelist has the following characteristics: • The lists are ordered. • The element of the list can access by index. • The lists are the mutable type. • A list can store the number of various elements.
  • 8.
    8 How to accesselements from a list? • We can use the index operator [] to access an item in a list. • In Python, indices start at 0. • So, a list having 6 elements will have an index from 0 to 5. • Trying to access indexes other than these will raise an IndexError. • The index must be an integer. We can't use float or other types, this will result in TypeError.
  • 9.
    9 How to accesselements from a list?
  • 10.
    10 How to accesselements from a list? print(List[-1])=5 print(List[-2])=4 print(List[-3])=3 print(list[-3:])= [3,4,5] print(list[:-1]) =[0,1,2,3,4] print(list[-3:-1]) =[3,4]
  • 11.
    11 Python List Built-infunctions • Python List append() Add a single element to the end of the list • Python List clear() Removes all Items from the List • Python List copy() returns a shallow copy of the list • Python List count() returns count of the element in the list
  • 12.
    12 Python List Built-infunctions • Python List extend() adds iterable elements to the end of the list • Python List index() returns the index of the element in the list • Python List insert() insert an element to the list • Python List pop() Removes element at the given index
  • 13.
    13 Python List Built-infunctions • Python List remove() Removes item from the list • Python List reverse() reverses the list • Python List sort() sorts elements of a list
  • 14.
    14 Python List Operations OperatorDescription Example Repetition The repetition operator enables the list elements to be repeated multiple times. l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8] L1*2 = [1, 2, 3, 4, 1, 2, 3, 4] Concatenation It concatenates the list mentioned on either side of the operator. l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8] Membership It returns true if a particular item exists in a particular list otherwise false. print(2 in l1) prints True. Iteration The for loop is used to iterate over the list elements. for i in l1: print(i) Output1 2 3 4 Length It is used to get the length of the list len(l1) = 4
  • 15.
    15 List Comprehensions Python •List comprehensions provide a concise way to create lists. • Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
  • 16.
    16 List Comprehensions Python •create a list of squares can be done by following >>> squares = [ ] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 17.
    17 List Comprehensions Python •Syntax • list_variable = [x for x in iterable] • list of squares can also be find using list comprehension as follows >>> squares = [x**2 for x in range(10)] • A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. • The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
  • 18.
    18 Tuples in Python •Tuples are used to store multiple items in a single variable. • Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. • A tuple is a collection which is ordered and unchangeable. • Tuples are written with round brackets.
  • 19.
    19 List vs Tuple ListTuple 1 The literal syntax of list is shown by the [ ]. The literal syntax of the tuple is shown by the (). 2 The List is mutable. The tuple is immutable. 3 List iteration is slower and is time consuming. Tuple iteration is faster. 4 Lists consume more memory Tuple consume less memory as compared to the list 5 The list is used in the scenario in which we need to store the simple collections with no constraints where the value of the items can be changed. The tuple is used in the cases where we need to store the read-only collections i.e., the value of the items cannot be changed. It can be used as the key inside the dictionary. 6 List provides many in-built methods. Tuples have less in-built methods.
  • 20.
    20 Creating a Tuple •A tuple is created by placing all the items (elements) inside parentheses ( ), separated by commas. • The parentheses are optional, however, it is a good practice to use them. • A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
  • 21.
    21 • # Differenttypes of tuples • # Empty tuple • my_tuple = () • print( my_tuple ) • # Tuple having integers • my_tuple = (1, 2, 3) • print( my_tuple ) • # tuple with mixed data types • my_tuple = (1, "Hello", 3.4) • print( my_tuple) • # nested tuple • my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) • print( my_tuple) Creating a Tuple
  • 22.
    22 Indexing • We canuse 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 will raise an IndexError. • The index must be an integer, so we cannot use float or other types. This will result in TypeError. How to access Tuple elements
  • 23.
    23 How to accessTuple elements
  • 24.
    24 Negative Indexing How toaccess Tuple elements • The tuple element can also access by using negative indexing. • The index of -1 denotes the rightmost element and -2 to the second last item and so on. • Example • Statement Output tuple1 = (1, 2, 3, 4, 5) print(tuple1[-1]) 5 print(tuple1[-4]) 2 print(tuple1[-3:-1]) (3, 4) print(tuple1[:-1]) (1, 2, 3, 4) print(tuple1[-2:]) (4, 5)
  • 25.
    25 The operators likeconcatenation (+), repetition (*), Membership (in) works in the same way as they work with the list. Basic Tuple operations Operator Description Example Repetition The repetition operator enables the tuple elements to be repeated multiple times. T1= (1, 2, 3, 4, 5) T2 = (6, 7, 8, 9) T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5) Concatenation It concatenates the tuple mentioned on either side of the operator. T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8, 9) Membership It returns true if a particular item exists in the tuple otherwise false print (2 in T1) prints True. Iteration The for loop is used to iterate over the tuple elements. for i in T1: print(i)Output1 2 3 4 5 Length It is used to get the length of the tuple. len(T1) = 5
  • 26.
    26 Python Tuple built-infunctions SN Function Description 1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise false. 2 len(tuple) It calculates the length of the tuple. 3 max(tuple) It returns the maximum element of the tuple 4 min(tuple) It returns the minimum element of the tuple. 5 tuple(seq) It converts the specified sequence to the tuple.
  • 27.
    27 Tuple Methods Method Description count()Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found
  • 28.
    28 Update Tuples • Tuplesare unchangeable, meaning that you cannot change, add, or remove items once the tuple is created. • Tuples are unchangeable or immutable.
  • 29.
    29 Unpacking Tuples • Whenwe create a tuple, we normally assign values to it. • This is called "packing" a tuple Example • Packing a tuple: • fruits = ("apple", "banana", "cherry") • But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking“. • fruits = ("apple", "banana", "cherry") • (green, yellow, red) = fruits • print(green) • print(yellow) • print(red) • Output: apple, yellow, red
  • 30.
    30 Tuple comprehension Tuple comprehension Example: T=(-1,2,-3,4,6) T=tuple(i for i in T if i>0) Output: [2,4,6] List comprehension Example: L=[-1,2,-3,4,6] L2=[i for i in L if i>0] Output: [2,4,6]
  • 31.
    31 Conversion of Listcomprehension to Tuple Example L=[1,2,3,4,5,6,7] T=tuple([i for i in L]) Print(T) Output: (1,2,3,4,5,6,7)
  • 32.
    32 Iterator In Python, aniterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__() . • An iterator is an object representing a stream of data. • It returns the data one element at a time. • A Python iterator must support a method called __next__() that takes no arguments and always returns the next element of the stream. • If there are no more elements in the stream, __next__() must raise the StopIteration exception. • Iterators don’t have to be finite. It’s perfectly reasonable to write an iterator that produces an infinite stream of data.
  • 33.
    33 Iterable • In Python,Iterable is anything you can loop over with a for loop. • An object is called an iterable if u can get an iterator out of it. • Calling iter() function on an iterable gives us an iterator. • Calling next() function on iterator gives us the next element. • If the iterator is exhausted(if it has no more elements), calling next() raises StopIteration exception.
  • 34.
  • 35.
    35 Iterating through anIterator • We use the next() function to manually iterate through all the items of an iterator. • When we reach the end and there is no more data to be returned, it will raise the StopIteration Exception. # define a list my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) # iterate through it using next() # Output: 4 print(next(my_iter))
  • 36.
    36 Iterating through anIterator # Output: 7 print(next(my_iter)) # next(obj) is same as obj.__next__() # Output: 0 print(my_iter.__next__()) # Output: 3 print(my_iter.__next__()) # This will raise error, no items left next(my_iter)
  • 37.
    37 Working of forloop for Iterators for <var> in <iterable>: <statement(s)>
  • 38.
    Multi dimensional list •A list represents a one-dimensional (1D), linear data structure. We can display a list’s elements from beginning to end in a straight line; for example: [9, 17, 88, 2, 17, 6, 45] We can locate an element uniquely within the list via a single integer index, its offset from the beginning of the list. In the example list above, element 88 is at index 2. Some kinds of information are better represented two-dimensionally, in a rectangular array of elements, also known as a matrix; for example, 100 14 8 22 71 0 243 68 1 30 90 21 7 67 112 115 200 70 150 8
  • 39.
    How are 2Dmatrices used? • Mathematicians can represent a system of equations in a matrix and use techniques from linear algebra to solve the system. • Computer scientists use 2D matrices to model the articulation of roboti arms. • Computer graphics programmers mathematically manipulate 2D matrices to transform data in 3D space and project it onto a 2D screen giving users the illusion of depth, motion, location. • Many classic games such as chess, checkers, Go, and Scrabble involve a 2D grid of board positions that naturally maps to a 2D matrix. • A word search puzzle is a rectangular array of letters, and a maze is simply a 2D arrangement of adjoining rooms, some of which are connected and others that are not.