0% found this document useful (0 votes)
19 views68 pages

Cse90d Unit2

Uploaded by

Abhishek Kumar
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)
19 views68 pages

Cse90d Unit2

Uploaded by

Abhishek Kumar
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/ 68

UNIT-2

Language Components and Collections


Components
Indenting Requirements

 Indentation refers to the spaces at the beginning of a code line.


 Where in other programming languages the indentation in code is for readability only,
Python uses indentation to indicate a block of code.
 The number of spaces is up to the programmer, but it has to be at least one.
 Python gives an error if skipped the indentation.
Indenting Requirements (Contd.)

 Example-
a) Input: if 5 > 2: Output: Five is greater than two!
print("Five is greater than two!“)

b) Input: if 5 > 2: Output: Expected an indented block


print("Five is greater than two!")
If Statement

 If statement is the most simple decision making statement.


 It is used to decide whether a certain statement or block of statements will be executed
or not.
 Condition after evaluation will be either true or false.
If Statement (Contd.)

 Example-
Input: i=10
if (i>15):
print (“10 is less than 15”)
print (“I am not in if”)
Output: I am not in if
Relational Operators

 Relational operators compares the values.


 It either returns True or False according to the condition.
 >: Greater than- True if left operand is greater than the right.
<: Less than- True if left operand is less than the right.
==: Equal to- True if both operands are equal.
!= Not equal to- True if operands are not equal.
>= Greater than or equal to- True if left operand is greater than or equal to the right.
<= Less than or equal to- True if left operand is less than or equal to the right.
Logical Operators

 Logical operators perform Logical AND, Logical OR and Logical NOT operations.
 and: Logical AND- True if both the operands are true.
or: Logical OR- True if either of the operands are true.
not: Logical NOT- True if operand is false.
Bitwise Operators

 Bitwise operators acts on bits and performs bit by bit operation.


 &: Bitwise AND
|: Bitwise OR
~: Bitwise NOT
^: Bitwise XOR
>>: Bitwise right shift
<<: Bitwise left shift
Python Loops

 Python has two primitive loop commands:


1. while loops
2. for loop
While Loop

 With the while loop we can execute a set of statements as long as a condition is true.
 Print i as long as i is less than 6:
i=1
while i<6:
print(i)
i+=1
While Loop- Break Statement

 With the break statement we can stop the loop even if the while condition is true:
 Exit the loop when i is 3:
i=1
while i<6:
print(i)
if i==3:
break
i+=1
While Loop- Continue Statement

 With the continue statement we can stop the current iteration, and continue with the next:
 Continue to the next iteration if i is 3:
i=0
while i<6
i+=1
if i==3:
continue
print (i)
While Loop- Else Statement

 With the else statement we can run a block of code once when the condition no longer is true:
 Print a message once the condition is false:
i=1
while i<6:
print(i)
i+=1
else:
print(“i is no longer less than 6”)
For Loop

 A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
 With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
 The for loop does not require an indexing variable to set beforehand.
 Print each fruit in a fruit list:
fruits=[“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
For Loop- Through String

 Even strings are iterable objects, they contain a sequence of characters:


 Loop through the letters in the word "banana":
for x in “banana”:
print(x)
For Loop- Break Statement

 With the break statement we can stop the loop before it has looped through all the items:
 Exit the loop when x is “banana”:
fruits=[“apple”, “banana”, “cherry”]
for x in fruits:
print(x)
if x==“banana”:
break
For Loop- Continue Statement

 With the continue statement we can stop the current iteration of the loop, and continue
with the next:
 Does not print banana:
fruits=[“apple”, “banana”, “cherry”]
for x in fruits:
if x==“banana”:
continue
print(x)
For Loop- Range() Function

 To loop through a set of code a specified number of times, we can use


the range() function,
 The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
 Using the range() function:
for x in range(6):
print(x)
For Loop- Else

 The else keyword in a for loop specifies a block of code to be executed when the loop is
finished.
 Print all numbers from 0 to 5, and print a message when the loop has ended.
for x in range(6):
print(x)
else:
print(“Finally finished!”)
For Loop- Nested Loop

 A nested loop is a loop inside a loop.


 The "inner loop" will be executed one time for each iteration of the "outer loop“,
 Print each adjective for every fruit:
adj=[“red”, “big”, “tasty”]
fruits=[“apple”, “banana”, “cherry”]
for x in adj:
for y in fruits:
print(x,y)
For Loop- Pass Statement

 If for loop, for some reason, has no content, put in pass statement to avoid getting an
error.
 for x in [0, 1, 2]:
pass
Collections
Introduction

Python programming language has four collection data types- list, tuple, set and dictionary.
But python also comes with a built-in module known as collections which has specialized
data structures which basically covers for the shortcomings of the four data types.
List

 Lists are used to store multiple items in a single variable.


 Lists are one of 4 built-in data types in Python used to store collections of data.
 Lists are created using square brackets.
 Creating list:
thislist=[“apple”, “banana”, “cherry”]
print(thislist)
List Items

 List items are ordered, changeable, and allow duplicate values.


 List items are indexed, the first item has index [0], the second item has index [1] and so on.
 List items can be of any datatypes:
list1=[“apple”, “banana”, “cherry”]
list2=[1, 5, 7, 9, 3]
list3=[True, False, False]
 A list can be of different datatypes:
List1=[“abc”, 34, True, 40, “male”]
List Items- Ordered

 When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
 If we add new items to a list, the new items will be placed at the end of the list.
List Items- Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.
List Items- Allow Duplicates

 Since lists are indexed, lists can have items with the same value:
 Lists allow duplicate values:
thislist=[“apple”, “banana”, “cherry”, “apple”, “cherry”]
print(thislist)
List Length

 To determine the number of items in a list, we use len() function.


 Print the number of items in the list:
thislist=[“apple”, “banana”, “cherry”]
print(len(thislist))
List type()

 From Python's perspective, lists are defined as objects with the data type 'list':
 mylist=[“apple”, “banana”, “cherry”]
print(type(mylist))
list() constructor

 It is also possible to use the list() constructor when creating a new list.
 To use this, we mandatorily enclose the values of list in double round-brackets.
 thislist=list((“apple”, “banana”, “cherry”))
print(thislist)
Tuple

 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.
 Tuples are written with round brackets.
 Creating tuple:
thistuple=(“apple”, “banana”, “cherry”)
print(thistuple)
Tuple Items

 Tuple items are ordered, unchangeable, and allow duplicate values.


 Tuple items are indexed, the first item has index [0], the second item has index [1] and so
on.
 Tuple items can be of any data type:
tuple1=(“apple”, “banana”, “cherry”)
tuple2=(1, 5, 7, 9, 3)
tuple3=(True, false, False)
 A tuple can contain different data types:
tuple1=(“abc”, 34, True, 40, “male”)
Tuple Items- Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Tuple Items- Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Tuple Items- Allow Duplicates

 Since tuple are indexed, tuples can have items with the same value.
 Tuples allow duplicate values:
thistuple=(“apple”, “banana”, “cherry”, “apple”, “cherry”)
print(thistuple)
Tuple Length

 To determine the number of items a tuple has, we use len() function.


 Print the number of items in the tuple:
thistuple=(“apple”, “banana”, “cherry”)
print(len(thistuple))
Tuple with One Item

 To create a tuple with only one item, we have to add a comma after the item.
 thistuple=(“apple”,)
print(type(thistuple))
Tuple type()

 From Python's perspective, tuples are defined as objects with the data type 'tuple':
 mytuple=(“apple”, “banana”, “cherry”)
print(type(mytuple))
tuple() Construtor

 It is also possible to use the tuple() constructor to make a tuple.


 To use this, we mandatorily enclose the values of list in double round-brackets.
 thistuple=tuple((“apple”, “banana”, “cherry”))
print(thistuple)
Set

 Sets are used to store multiple items in a single variable.


 Set is one of 4 built-in data types in Python used to store collections of data.
 Sets are written with curly brackets.
 Creating set:
thisset={“apple”, “banana”, “cherry”}
print(thisset)
Set Items

 Set items are unordered, unchangeable, and do not allow duplicate values.
 Set items can be of any data type:
set1={“apple”, “banana”, “cherry”}
set2={1, 5, 7, 9, 3}
Set3={True, False, False}
 A set can contain different data types:
set1={“abc”, 34, True, 40, “male”}
Set Items- Unordered

 Unordered means that the items in a set do not have a defined order.
 Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Set Items- Unchangeable

 Sets are unchangeable, meaning that we cannot change the items after the set has
been created.
 Once a set is created, you cannot change its items, but you can add new items.
Set Items- Duplicates not Allowed

 Sets cannot have two items with the same value.


 Duplicate values will be ignored:
thisset={“apple”, “banana”, “cherry”, “apple”}
print(thisset)
Length of Set

 To determine the number of items in a set, we use len() method.


 The number of items in a set:
thisset={“apple”, “banana”, “cherry”}
print(len(thisset))
Set type()

 From Python's perspective, sets are defined as objects with the data type 'set„.
 myset={“apple”, “banana”, “cherry”}
print(type(myset))
set() Constructor

 It is also possible to use the set() constructor to make a set.


 To use this, we mandatorily enclose the values of list in double round-brackets.
 thisset=set((“apple”, “banana”, “cherry”))
print(thisset)
Dictionary

 Dictionaries are used to store data values in key:value pairs.


 Dictionaries are written with curly brackets, and have keys and values,
 Creating dictionary:
thisdict={
“brand”: ”Ford”,
“model”: ”Mustang”,
“year”: 1964
}
print(thisdict)
Dictionary Items

 Dictionary items are unordered, changeable, and does not allow duplicates.
 Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
 Print the "brand" value of the dictionary:
thisdict={
“brand”: ”Ford”,
“model”: ”Mustang”,
“year”: 1964
}
print(thisdict[“brand”])
Dictionary Items (Contd.)

The values in dictionary items can be of any data type:


thisdict={
“brand”: “Ford”,
“electric”: False,
“year”: 1964,
“colors”: [“red”, “white”, “blue”]
}
Dictionary Items- Unordered

When we say that dictionaries are unordered, it means that the items does not have a
defined order, we cannot refer to an item by using an index.
Dictionary Items- Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Dictionary Items- Duplicates not Allowed

 Dictionaries cannot have two items with the same key.


 Duplicate values will overwrite existing values:
thisdict={
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964,
“year”: 2020
}
print(thisdict)
Dictionary Length

 To determine the number of items in a dictionary, use the len() function.


 Print the number of items in the dictionary:
print(len(thisdict))
Dictionary type()

 From Python's perspective, dictionaries are defined as objects with the data type 'dict„.
 Print the data type of a dictionary:
thisdict={
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
print(type(thisdict))
Sorting Dictionaries

 Python dictionary is the collection of data which stored in the key-value form. Each key is
associated with its value. It is mutable in nature, which means we can change data after
its creation.
 It is the unordered collection of the data and allows storing duplicate values, but the key
must be unique.
 Dictionary is declared using the curly braces {}, and the key-value pair is separated by a
comma.
 dict1 = {'name': 'Devansh', 'age': 22, 'Rollno':90014}
 print(dict1)
Cont..

 Why need to sort the dictionary


 The search time complexity of the list is O(n), and the dictionary has search time
complexity 0(1), which makes that the dictionary is faster than the list. The dictionary can
be used in place for list whenever it needs.
 The sorting allows us to analyze the data efficiently when we are working with the data-
structure.
 A sorted dictionary provides a better understanding to handle the complex operations.
Let's understand the various ways to sort the dictionary.

 Sorting by keys
 Sorting by values
 Sorting Algorithm
 Reversing the sorted order
Sorting By Keys and Values

 Python offers the built-in keys functions keys() and values() functions to sort the dictionary.
It takes any iterable as an argument and returns the sorted list of keys.
 We can use the keys to sort the dictionary in the ascending order. Let's understand the
following example.
 names = {1:'Alice' ,2:'John' ,4:'Peter' ,3:'Andrew' ,6:'Ruffalo' ,5:'Chris' }
 #print a sorted list of the keys
 print(sorted(names.keys()))
 #print the sorted list with items.
 print(sorted(names.items()))
Output of Example

 [1, 2, 3, 4, 5, 6]
 [(1, 'Alice'), (2, 'John'), (3, 'Andrew'), (4, 'Peter'), (5, 'Chris'), (6, 'Ruffalo')]
Sorting Algorithm

 There are various sorting algorithm to sort a dictionary; we can use other arguments in the
sorted method. Let's understand the following example.
 daynames = { 'one' : 'Monday' , 'six' : 'Saturday' ,'three' : 'Wednesday' , 'two' : 'Tuesday' , 'fi
ve': 'Friday' , 'seven': 'Sunday' }
 print(daynames)
 number = { 'one' : 1 , 'two' : 2 , 'three' : 3 , 'four' : 4 , 'five' : 5 , 'six' : 6 , 'seven' : 7}
 print(sorted(daynames , key=number.__getitem__))
 print([daynames[i] for i in sorted(daynames , key=number.__getitem__)])
Output

 {'one': 'Monday', 'six': 'Saturday', 'three': 'Wednesday', 'two': 'Tuesday', 'five': 'Friday', 'seven':
'Sunday'}
 ['one', 'two', 'three', 'five', 'six', 'seven']
 ['Monday', 'Tuesday', 'Wednesday', 'Friday', 'Saturday', 'Sunday']
Reverse the sorted Order

 The dictionary can be reversed using the reverse argument. Let's understand the following
example.
 Example -
 a = {'a':2 ,'b':1 ,'c':3 ,'d':4 ,'e':5 ,'f':6 }
 print(sorted(a.values() , reverse= True))
 Output:
 [6, 5, 4, 3, 2, 1]
Copying Collections

 Copy in Python
 The assignment operator is used to create the copy of the Python object, but this is not
true; it only create the binding between a target and object. When we use the
assignment operator, instead of creating a new object, it creates a new variable that
shares the old object's reference.
 The copies are helpful when a user wants to make changes without modifying the original
object at the same time. A user also prefers to create a copy to work with mutable
objects.
Example -

 list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 'a']]


 list2 = list1

 list2[1][2] = 4

 print('Old List:', list1)
 print('ID of Old List:', id(list1))

 print('New List:', list2)
 print('ID of New List:', id(list2))
Output of Example

 Old List: [[1, 2, 3], [4, 5, 4], [7, 8, 'a']]


 ID of Old List: 1909447368968
 New List: [[1, 2, 3], [4, 5, 4], [7, 8, 'a']]
 ID of New List: 1909447368968

You might also like