Unit 3
Unit 3
Python Collections
There are four collection data types in the Python programming
language:
• List:
It is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple:
It is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set:
It is a collection which is unordered and unindexed. No duplicate
members
• Dictionary :
It is a collection which is unordered, changeable and indexed. No
duplicate members.
Introduction
• Programs commonly need to store a large number of values.
Suppose, for instance, that you need to read 100 numbers,
compute their average, and then find out how many of the
numbers are above the average.
• Your program first reads the numbers and computes their
average, then compares each number with the average to
determine whether it is above the average.
• In order to accomplish this task, the numbers must all be stored
in variables.
• To do this, you would have to create 100 variables and
repeatedly write almost identical code 100 times. Writing a
program this way is impractical. So, how do you solve this
problem?
List
• A list can store a collection of data of any size
• Lists are mutable, and hence, they can be altered even after their creation.
List: A list is a built-in sequence type in Python, defined by the list class. It's a
collection of ordered, mutable elements that can be of different data
types.
LIST BASICS
Creation of Lists
Creating list using the list class with the list() constructor
list1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"]) # Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c,d
For convenience, you may create a list using the following syntax:
6
How to Create Lists
• The elements in a list are separated by commas and are enclosed by a pair of
brackets ([]).
Syntax:
list_name=[list_element1,list_element2,list_element3,……]
Ex:
list = [2, "three", 4]
list 1= [“Hi",6 , "three", 4]
list2=[10,20,[40,60],"hai",80,[20,"python"]]
list3=[]
• A list within another list is said to be nested and the inner list is often called
a sublist.
• Finally, there is a special list that contains no elements. It is called the empty
list and is denoted [].
Note:
A list can contain the elements of same type or mixed type
Strings
• A String is a sequence of characters.
9
Python Built-in functions of list
“len()” function
The len() function returns the number of items
(length) in a list
Python Built-in functions of list
“max()” function
Calculates maximum of all the elements in the List
Syntax: max(List)
Python Built-in functions of list
“min()” function
Calculates minimum of all the elements in the List
Syntax: min(List)
Python Built-in functions of list
“sum() “function
Calculates sum of all the elements of List.
Syntax: sum(List)
Note: Sum is calculated only for Numeric values, elsewise throws TypeError.
Python Built-in functions of list
random.shuffle() function
Shuffle a list (reorganize the order of the list items)
items.
The shuffle() method takes a sequence (list, string,
or tuple) and reorganize the order of the items.
Python Built-in functions
The List operators
in operator
– The ‘in’ operator is used to check if a value exists in the list or
not.
– Evaluates to true if the element present in the list and false
otherwise.
The List operators
not in operator
– The ‘not in’ operator is used to check if a value exists in the list
or not.
– Evaluates to true if the element is not present in the list and
false otherwise.
The List operators
“+” Operator
The concatenation operator + is used to
join the list elements.
The List operators
“*” Operator
The multiplication operator “ * “ is used to
replicate the elements in the list.
Index Operator []
• The elements of the list can be accessed by using the index
operator [].
Syntax : variable_name [Index value]
The first element of the list is stored at the 0th index, the second
element of the list is stored at the 1st index, and so on.
Index Operator []
Negative indexing
• Python provides us the flexibility to use the negative indexing
also.
• The negative indices are counted from the right.
• The last element (right most) of the list has the index -1, its
adjacent left element is present at the index -2 and so on until the
left most element is encountered.
negative indexing
29
List Comprehension
30
List Comprehension
31
Explanation
• In line 1, list1 is created from an expression
using a for clause.
• The numbers in list1 are 0, 1, 2, 3, and 4.
• Each number in list2 is half of the
corresponding number in list1 (line 5).
• In line 9, list3 consists of the numbers whose
value is less than 1.5 in list2
List Methods:Append, insert, remove
['apple', 'cherry']
33
List Methods: Pop, clear, del
['apple', 'banana']
[]
['banana', 'cherry']
34
Splitting a String into a List
• The str class contains the split method, which is useful for splitting items
in a string into a list.
For example, the following statement:
items = "Jane John Peter Susan".split()
splits the string Jane John Peter Susan into the list
['Jane', 'John', 'Peter', 'Susan']
In this case the items are delimited by spaces in the string. You can use a
non space delimiter.
For example, the following statement:
items = "09/20/2012".split("/")
splits the string 09/20/2012 into the list ['09', '20', '2012'].
Lists are Mutable
• Unlike strings, lists are mutable. This means we can change an item in a list
by accessing it directly as part of the assignment statement.
• Using the indexing operator (square brackets) on the left side of an
assignment, we can update one of the list items.
Contd..
• An assignment to an element of a list is called item assignment. Item
assignment does not work for strings because strings are immutable.
• By combining assignment with the slice operator we can update several
elements at once.
• We can also remove elements from a list by assigning the empty list to
them.
some examples that use the append, count, extend, index, and insert
methods:
some examples that use the insert, pop, remove, reverse, and sort
methods:
Contd..
•The word mutator means that the list is changed by the method but nothing is returned
(actually None is returned).
•A hybrid method is one that not only changes the list but also returns a value as its result
Inputting Lists
• The data can be read from console into a list.
• So that we need to enter one data item per line and append it to a
list in a loop.
For example, the following code reads ten numbers one per line
into a list
list=[]
print("enter 10 integers")
for i in range(10):
list.append(eval(input("enter Integers:")))
print(list)
Inputting Lists
• It is more convenient to enter the data in one line separated by
spaces.
• To extract data from single input line we can use split() method
For example, the following code reads ten numbers separated by
spaces from one line into a list:
s=input('enter 10 number')
items=s.split(",")
list=[eval(x) for x in items]
•You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in list1 will automatically
also be made in list2 46
Copying Lists
Line 1
and2
Line:7
Output:
True
False
True Line 8 and 9
True
[5, 82, 83]
Cloning Lists
lst = [3, 1, 2, 6, 4, 2]
printList(lst)
Anonymous list
53
Pass By Value
• Python uses pass-by-value to pass arguments to
a function.
• There are important differences between passing
the values of variables of numbers and strings
and passing lists.
– Immutable objects
– Changeable objects
54
Pass By Value (Immutable objects)
• For an argument of a number or a string, the
original value of the number and string outside
the function is not changed,
• because numbers and strings are immutable in
Python.
55
Pass By Value (changeable objects)
• For an argument of a list, the value of the
argument is a reference to a list;
• this reference value is passed to the function.
• Semantically, it can be best described as pass-by-
sharing, i.e., the list in the function is the same as
the list being passed.
• So if you change the list in the function, you will
see the change outside the function.
56
PassListArgument.py
Contd…
O/p:
• The function add appends x to list if x is not in the list (lines 1–5). When the
function is executed for the first time (line 8), the default value [] for the
argument lst is created.
• add(1) adds 1 to list. When the function is called again (line 11), list is now
[1] not [], because list is created only once.
• After add(2) is executed, list becomes [1, 2]. In line 14, the list argument
[11, 12, 13, 14] is given, and this list is passed to list.
• In line 17, the default list argument is used. Since the default list now is [1,
2], after invoking add(4), the default list becomes [1, 2, 4].
DefualtNoneListArgument.py
Contd…
[1]
O/p:
[2]
[10, 11, 12, 13, 3]
[4]
• Here a new empty list is created every time the add function is called
without a list argument (line 3).
• If the list argument is given when invoking the function, the default list is
not used.
Returning a List from a Function
• When a function returns a list, the list’s reference value is returned.
Returning a List from a Function
result.
66
Linear Search
Key List
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
67
Linear Search
Binary Search
For binary search to work, the elements in the list
must already be ordered. Without loss of generality,
assume that the list is in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
69
Binary Search
Consider the following three cases:
• If the key is less than the middle element, you only need
to search the key in the first half of the list.
• If the key is equal to the middle element, the search
ends with a match.
• If the key is greater than the middle element, you only
need to search the key in the second half of the list.
70
Binary Search
Key List
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
71
Binary Search
72
Binary Search
# Use binary search to find the key in the list
def binarySearch(lst, key):
low = 0
high = len(lst) - 1
- insertion point - 1.
74
Chapter-2
Tuples, Sets, and Dictionaries
Introducton
You can also create a tuple from a string. Each character in the string
becomes an element in the tuple. For example:
# Create a tuple from a string
t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c']
Inbuilt functions for tuple
• len(tuple):It calculates the length of the tuple.
Inbuilt functions for tuple
• max(tuple) :It returns the maximum element
of the tuple.
Inbuilt functions for tuple
• min(tuple) :It returns the minimum element of
the tuple.
Inbuilt functions for tuple
• Sum() : Returns the sum of all the elements in
the tuple
Inbuilt functions for tuple
• index(x): Returns the index of the element x
Inbuilt functions for tuple
• count(x) : Returns the number of occurrences
of element x
Indexing and slicing
• Tuples are like lists , so indexing and slicing of
tuple is similar to that of lists.
• The indexing operator “[ ]” is uses to access
elements of a tuple.
• The index must be an integer; so we cannot use
float or other types. This will result in “type error”.
• 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
Operations on tuples
• Operators can be used to concatenate or
multiply tuples.
• Concatenation is done with the ”+” operator
• Multiplication is done with the ”*” operator.
Concatenation(using “+” operator)
Repetition operator
• “*” : The multiplication operator is used to
replicate the elements of the tuple.
Passing variable length arguments to tuples
105
Contd…
• A set can contain the elements of the same type or mixed
types.
• For example, s = {1, 2, 3, "one", "two", "three"} is a set that
contains numbers and strings.
• Each element in a set must be hashable.
• Each object in Python has a hash value and an object is
hashable i.e., hash value never changes during its lifetime.
• Sets use hashing to store and retrieve elements efficiently.
• Internally, each element’s hash is used to determine where to
store it in memory 106
Manipulating and Accessing Sets
>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 2}
>>> s1 == s2
True
>>> s1 != s2
False
>>>
110
Comparison Operators
Note that it makes no sense to compare the sets using the
conventional comparison operators (>, >=, <=, <), because the
elements in a set are not ordered. However, these operators have
special meaning when used for sets.
112
Set Operations
Python provides the methods for performing
set union, intersection, difference, and
symmetric difference operations.
Set Operation-- (union, |)
•The union of two sets is a set that contains all the elements from
both sets.
•we can use the union method or the | operator to perform this
operation.
For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.union(s2)
{1, 2, 3, 4, 5}
>>>
>>> s1 | s2
{1, 2, 3, 4, 5}
>>>
114
Set Operation --(intersection, &)
•The intersection of two sets is a set that contains the elements that
appear in both sets.
• we can use the intersection method or the & operator to perform
this operation.
For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.intersection(s2)
{1}
>>>
>>> s1 & s2
{1}
115
>>>
Set Operation (difference, -)
•The difference between set1 and set2 is a set that contains the
elements in set1 but not in set2.
•we can use the difference method or the - operator to perform
this operation.
•For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.difference(s2)
{2, 4}
>>>
>>> s1 - s2
{2, 4}
>>>
116
Set Operations (symetric_difference, ^)
•The symmetric difference (or exclusive or) of two sets is a set that
contains the elements in either set, but not in both sets.
• we can use the symmetric_difference method or the ^ operator to
perform this operation.
•For example:
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.symmetric_difference(s2)
{2, 3, 4, 5}
>>>
>>> s1 ^ s2
{2, 3, 4, 5}
>>> 117
Comparing the Performance of Sets and
Lists
• The keys are like an index operator. In a list, the indexes are
integers. In a dictionary, the key must be a hashable object.
120
Dictionary
A dictionary cannot contain duplicate keys. Each key maps to one value.
A key and its corresponding value form an item (or entry) stored in a
dictionary. The data structure is a called a “dictionary” because it
resembles a word dictionary, where the words are the keys and the
words’ definitions are the values. A dictionary is also known as a map,
which maps each key to a value
121
Creating a Dictionary
To create a dictionary by enclosing the items inside a pair of curly
braces ({}). Each item consists of a key, followed by a colon, followed
by a value. The items are separated by commas. For example, the
following statement:
dictionary = {} # Create an empty dictionary
students = {"111-34-3434":"John", "132-56-6290":"Peter"}
Above example creates a dictionary with two items. The item is in
the form key:value. The key in the first item is 111-34-3434, and its
corresponding value is John. The key must be of a hashable type
such as numbers and strings. The value can be of any type.
122
Adding/Modifying Entries/Retrieving values
For example,
dictionary["susan"] = 50
123
Adding/Modifying Entries/Retrieving values
To retrieve a value
Syntax: dictionaryName[key]
If the key is in the dictionary, the value for the key is returned.
Otherwise, a KeyError exception is raised
124
Deleting Entries
To delete an entry from a dictionary
125
Looping Entries
You can use a for loop to traverse all keys in the dictionary.
Syntax:
for key in dictionary:
print(str(key )+ ":" + str(dictionary[key]))
Looping Entries
The len operator
128
Testing Whether a Key Is in a Dictionary
129
Equality Test
130
The Dictionary Methods
dict
keys(): tuple Returns a sequence of keys.
values(): tuple Returns a sequence of values.
items(): tuple Returns a sequence of tuples (key, value).
clear(): void Deletes all entries.
get(key): value Returns the value for the key.
pop(key): value Removes the entry for the key and returns its value.
popitem(): tuple Returns a randomly-selected key/value pair as a tuple and
removes the selected entry.
131
The Dictionary Methods
132