0% found this document useful (0 votes)
30 views44 pages

Python Unit - II

Unit II of the Python document covers conditional statements, including if, else, elif, and nested if statements, along with string operations and looping statements like while and for loops. It explains the syntax and usage of these constructs, including examples for clarity. Additionally, it discusses control statements such as break, continue, and pass, and introduces lists as a fundamental data structure in Python.

Uploaded by

Aathi
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)
30 views44 pages

Python Unit - II

Unit II of the Python document covers conditional statements, including if, else, elif, and nested if statements, along with string operations and looping statements like while and for loops. It explains the syntax and usage of these constructs, including examples for clarity. Additionally, it discusses control statements such as break, continue, and pass, and introduces lists as a fundamental data structure in Python.

Uploaded by

Aathi
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/ 44

Python: Unit - II

UNIT - II
Conditional Statement
if Statement
The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If expression evaluates to FALSE, then the first set of code after the end
of the if statement(s) is executed.

Python supports the usual logical conditions from mathematics:


➢ Equals: a == b
➢ Not Equals: a != b
➢ Less than: a < b
➢ Less than or equal to: a <= b
➢ Greater than: a > b
➢ Greater than or equal to: a >= b
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")

Department of CS&IT, S.S.D.M College. 1


Python: Unit - II

Python relies on indentation (whitespace at the beginning of a line) to define scope in


the code. Other programming languages often use curly-brackets for this purpose.
Example:
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

if…else… Statement
An else statement can be combined with an if statement. An else statement contains the
block of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if expression:
statement(s)
else:
statement(s)

Example:
a = 33
b = 200

Department of CS&IT, S.S.D.M College. 2


Python: Unit - II

if b > a:
print("b is greater than a")
else
print("a is greater than b")

elif Statement
The elif statement allows to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elif statements following an
if.
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example:
var = 100
if var == 200:
print ("Executes 1st Expression, Var is : ",var)
elif var == 150:
print ("Executes 2nd Expression, Var is : ",var)
elif var == 100:
print ("Executes 3rd Expression, Var is : ",var)
else:
print ("Executes Last Expression, Var is : ",var)

Department of CS&IT, S.S.D.M College. 3


Python: Unit - II

nested if Statement
There may be a situation need to check for another condition after a condition resolves
to true. In such a situation, the nested if construct is used.
In a nested if construct, an if... elif... else construct inside another if... elif... else
construct.
Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
else var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"

Department of CS&IT, S.S.D.M College. 4


Python: Unit - II

String Operations
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Example: 'hello' is the same as "hello".

Assign String
a = "Hello"
print(a)

Multiline String
It can assign to a variable by using three double quotes or single qutoes
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a
string with a length of 1.
Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])

Check String Length


To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))

Department of CS&IT, S.S.D.M College. 5


Python: Unit - II

Check String
To check if a certain phrase or character is present in a string, we can use the keyword
in.
txt = "The best things in life are free!"
print("free" in txt) #Present

txt = "The best things in life are free!"


print("expensive" not in txt) #Not Present

Slicing String
Return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
b = "Hello, World!"
print(b[2:5])

Slice From the Start


By leaving out the start index, the range will start at the first character
b = "Hello, World!"
print(b[:5])

Slice To the End


By leaving out the end index, the range will go to the end
b = "Hello, World!"
print(b[2:])

Built in Methods
➢ Upper Case
➢ Lower Case
➢ Replace String
➢ Remove Whitespace
➢ Split String

Department of CS&IT, S.S.D.M College. 6


Python: Unit - II

Upper Case
It returns the string in Upper Case, upper()
a = "Hello, World!"
print(a.upper())

Lower Case
It returns the string in Lower Case, lower()
a = "Hello, World!"
print(a.lower())

Replace String
Replace the string with another string, replace()
a = "Hello, World!"
print(a.replace("H", "J"))

Remove Whitespace
Removes any whitespace from the beginning or the end, strip()
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Split String
Splits the string into substrings if it finds instances of the separator
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String Concatenation
To concatenate or combine two strings by using the + operator
a = "Hello"
b = "World"
c=a+b
print(c)

Department of CS&IT, S.S.D.M College. 7


Python: Unit - II

Format Strings
Combine strings and number by using format() method.
The format() methods takes the passed arguments, formats them, and places them in
the string where the placeholders {} are
age = 36
txt = "My name is Roy, and I am {}"
print(txt.format(age))
The format() method takes unlimited number of arguments, and are placed into the
respective placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Use index numbers {0} to be sure the arguments are placed in the correct placeholders
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Escape Character
✓ To insert characters that are illegal in a string, use an escape character.
✓ An escape character is a backslash \ followed by the character you want to insert.
txt = "We are the so-called "Vikings" from the north." #Illegal Format
✓ To fix this problem use escape characters \”
txt = "We are the so-called \"Vikings\" from the north."

Other Special Characters


Code Result
\’ Single Quote
\\ Backslash
\n New line
\r Carriage Return

Department of CS&IT, S.S.D.M College. 8


Python: Unit - II

\t Tab
\b Backspace
\f Form Feed
\ooo Octal Value
\xhh Hex Value

Looping Statements
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
Python programming language provides following types of loops: while, for

while Loop Statements


A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
while expression:
statement(s)

Department of CS&IT, S.S.D.M College. 9


Python: Unit - II

Here, statement(s) may be a single statement or a block of statements. The condition


may be any expression, and true is any non-zero value. The loop iterates while the condition is
true.
When the condition becomes false, program control passes to the line immediately
following the loop.
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. Must use caution
when using while loops because of the possibility that this condition never resolves to a FALSE
value. This results in a loop that never ends. Such a loop is called an infinite loop.
count = 0
while (count < 9):
print ('The count is:', count)

Using else Statement with While Loop


Python supports to have an else statement associated with a loop statement.
➢ If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
count = 0
while (count < 5):
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")

Single Statement Suites


Similar to the if statement syntax, if while clause consists only of a single statement, it
may be placed on the same line as the while header.
count = 0
while (count < 9): print ('The count is:', count)

Department of CS&IT, S.S.D.M College. 10


Python: Unit - II

nested while Loop


The syntax for a nested while loop statement in Python programming language is
while expression:
while expression:
statement(s)
statement(s)
Example:
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print (i, " is prime")
i=i+1

for Loop Statements


It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax:
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.

Department of CS&IT, S.S.D.M College. 11


Python: Unit - II

for letter in 'Python': # First Example


print ('Current Letter :', letter)

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print ('Current fruit :', fruit)

Iterating by Sequence Index


An alternative way of iterating through each item is by index offset into the sequence
itself.
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])

nested for Loop Statements


Python programming language allows to use one loop inside another loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

Using else Statement with For Loop


Python supports to have an else statement associated with a loop statement
➢ If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop

Department of CS&IT, S.S.D.M College. 12


Python: Unit - II

print num, 'is a prime number'


break

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements: break, continue, pass

break Statement
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.
The most common use for break is when some external condition is triggered requiring
a hasty exit from a loop. The break statement can be used in both while and for loops.
In nested loops, the break statement stops the execution of the innermost loop and start
executing the next line of code after the block.
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)

var = 10 # Second Example


while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break

continue Statement
It returns the control to the beginning of the while loop. The continue statement rejects
all the remaining statements in the current iteration of the loop and moves the control back to
the top of the loop.
The continue statement can be used in both while and for loops.

Department of CS&IT, S.S.D.M College. 13


Python: Unit - II

for letter in 'Python': # First Example


if letter == 'h':
continue
print ('Current Letter :', letter)

var = 10 # Second Example


while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)

pass Statement
It is used when a statement is required syntactically but you do not want any command
or code to execute.
The pass statement is a null operation; nothing happens when it executes.
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

LISTS
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 some built-in types of sequences, but the most common ones are lists and
tuples.

Python Lists
The list is a most versatile datatype available in Python which can be written as a list
of comma-separated values (items) between square brackets. Important thing about a list is that
items in a list need not be of the same type. list1 = ['physics', 'chemistry', 1997, 2000];

Department of CS&IT, S.S.D.M College. 14


Python: Unit - II

list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

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] etc.

Ordered
Lists are ordered, it means that the items have a defined order, and that order will not
change.
New items to a list, the new items will be placed at the end of the list.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value
list1 = ['physics', 'chemistry', 1997, 2000, 'chemistry'];

List Length
To determine how many items a list has, use the len() function
list1 = ['physics', 'chemistry', 1997, 2000, 'chemistry'];
print(len(list1))

Access List Items


List items are indexed and you can access them by referring to the index number
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
The first item has 0 index

Department of CS&IT, S.S.D.M College. 15


Python: Unit - II

Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range of Indexes
A range of indexes specifies where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
The search will start at index 2 (included) and end at index 5 (not included)
By leaving out the start value, the range will start at the first item.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

Check if Item Exists


To determine if a specified item is present in a list use the in keyword
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

Change List Items


To change the value of a specific item, refer to the index number
thislist = ["apple", "banana", "cherry"]

Department of CS&IT, S.S.D.M College. 16


Python: Unit - II

thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values


To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Insert more items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
insert less items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items
To insert a new list item, without replacing any of the existing values, we can use the
insert() method.
The insert() method inserts an item at the specified index
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

Add List Items


Append Items
To add an item to the end of the list, use the append() method
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")

Department of CS&IT, S.S.D.M College. 17


Python: Unit - II

print(thislist)

Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Extend List
To append elements from another list to the current list, use the extend() method
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

Add Any Iterable


The extend() method does not have to append lists, you can add any iterable object
(tuples, sets, dictionaries etc.)
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Remove List Items


Remove Specified Item
The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Department of CS&IT, S.S.D.M College. 18


Python: Unit - II

Remove Specified Index


The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
If index is not specified, the pop() method removes the last item.
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
The del keyword also removes the specified index
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
The del keyword can also delete the list completely.
thislist = ["apple", "banana", "cherry"]
del thislist

Clear the List


The clear() method empties the list.
The list still remains, but it has no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Loop Lists
Loop Through a List
Loop through the list items by using a for loop
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Loop Through the Index Numbers


Can also loop through the list items by referring to their index number.

Department of CS&IT, S.S.D.M College. 19


Python: Unit - II

Use the range() and len() functions to create a suitable iterable.


thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])

List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter
"a" in the name.
Without list comprehension you will have to write a for statement with a conditional
test inside
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)

Sort Lists
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically, ascending, by
default

Alphabetical Sort
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Department of CS&IT, S.S.D.M College. 20


Python: Unit - II

Numerical Sort
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)

Sort Descending
To sort descending, use the keyword argument reverse = True
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)

Copy Lists
Copy a List
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.
There are ways to make a copy, one way is to use the built-in List method copy().
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

Join Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

Department of CS&IT, S.S.D.M College. 21


Python: Unit - II

Another way to join two lists are by appending all the items from list2 into list1, one
by one
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Use the extend() method, which purpose is to add elements from one list to another list.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)

TUPLES
A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
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] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after
the tuple has been created.
Allow Duplicates
Since tuple are indexed, tuples can have items with the same value
thistuple = ("apple", "cherry", "apple", "cherry")
print(thistuple)

Department of CS&IT, S.S.D.M College. 22


Python: Unit - II

Tuple Length
To determine how many items a tuple has, use the len() function
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

Create Tuple with One Item


To create a tuple with only one item, must add a comma after the item, otherwise Python
will not recognize it as a tuple.
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types


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")

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.
thistuple = tuple(("apple", "banana", "cherry"))# note the double round-brackets
print(thistuple)

Python - Access Tuple Items


Tuple item can access by referring to the index number, inside square brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Department of CS&IT, S.S.D.M College. 23


Python: Unit - II

Negative Indexing
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the
second last item etc.
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

Range of Indexes
Specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
By leaving out the start value, the range will start at the first item.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the list.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the tuple.
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword.
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Python - Update Tuples


Tuples are unchangeable, meaning that you cannot change, add, or remove items once
the tuple is created. But there are some workarounds.

Department of CS&IT, S.S.D.M College. 24


Python: Unit - II

Change Tuple Values


Once a tuple is created, cannot able to change its values. Tuples are unchangeable, or
immutable as it also is called.
But there is a workaround. Convert the tuple into a list, change the list, and convert the
list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Add Items
Once a tuple is created, cannot add items to it.
thistuple = ("apple", "banana", "cherry")
thistuple.append("orange") # This will raise an error
print(thistuple)
Just like the workaround for changing a tuple, convert it into a list, add your item(s),
and convert it back into a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

Remove Items
Tuples are unchangeable, so cannot remove items from it, but can able to use the same
workaround as used for changing and adding tuple items
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

delete tuple
thistuple = ("apple", "banana", "cherry")

Department of CS&IT, S.S.D.M College. 25


Python: Unit - II

del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Python - Unpack Tuples


When create a tuple, normally assign values to it. This is called "packing" a tuple
fruits = ("apple", "banana", "cherry")
But, in Python, can able 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)

Using Asterisk*
If the number of variables is less than the number of values, add an * to the variable
name and the values will be assigned to the variable as a list to collect the remaining.
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
If the asterix is added to another variable name than the last, Python will assign values
to the variable until the number of values left matches the number of variables left
fruits = ("apple", "mango", "papaya", "pineapple", "strawberry", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)

Python - Loop Tuples


Loop through the tuple items by using a for loop.
thistuple = ("apple", "banana", "cherry")

Department of CS&IT, S.S.D.M College. 26


Python: Unit - II

for x in thistuple:
print(x)

Loop Through the Index Numbers


Also, can able to loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])

Using a While Loop


Loop through the list items by using a while loop.
Use the len() function to determine the length of the tuple, then start at 0 and loop
through the tuple items by refering to their indexes.
Remember to increase the index by 1 after each iteration.
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1

Python - Join Tuples


To join two or more tuples, you can use the + operator
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

Multiply Tuples
Multiply the content of a tuple a given number of times, can use the * operator.
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

Department of CS&IT, S.S.D.M College. 27


Python: Unit - II

Sets
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.
A set is a collection which is both unordered and unindexed. Sets are written with curly
brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

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.

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.

Duplicates Not Allowed


Sets cannot have two items with the same value.
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)

Length of a Set
To determine how many items a set has, use the len() method.
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Department of CS&IT, S.S.D.M College. 28


Python: Unit - II

Set Items - Data Types


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"}

The set() Constructor


It is also possible to use the set() constructor to make a set.
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

Python – Access Items


Accessing items in a set by referring to an index or a key is not possible.
But can able to loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Check “banana” is present in the set.
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

Python – Add Items


Once a set is created, change its items is not possible, but can able to add new items.
To add one item to a set use the add() method.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

Add Sets
To add items from another set into the current set, use the update() method.

Department of CS&IT, S.S.D.M College. 29


Python: Unit - II

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)

Add Any Iterable


The object in the update() method does not have be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)

Python – Remove Items


To remove an item in a set, use the remove(), or the discard() method.
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
If the item to remove does not exist, remove() will raise an error.
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
If the item to discard does not exist, discard() will NOT raise an error.

pop()
Use the pop() method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so will not know what item that gets removed.
The return value of the pop() method is the removed item.
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

Department of CS&IT, S.S.D.M College. 30


Python: Unit - II

clear()
The clear() method empties the set
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

del
The del keyword will delete the set completely
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

Python – Loop Sets


Loop through the set items by using a for loop.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

Python – Join Sets


There are several ways to join two or more sets in Python.
Use the union() method that returns a new set containing all items from both sets, or
the update() method that inserts all the items from one set into another.
The union() method returns a new set with all items from both sets
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
The update() method inserts the items in set2 into set1
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Both union() and update() will exclude any duplicate items.

Department of CS&IT, S.S.D.M College. 31


Python: Unit - II

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

The intersection() method will return a new set, that only contains the items that are
present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)

Keep All, But NOT the Duplicates


The symmetric_difference_update() method will keep only the elements that are NOT
present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

The symmetric_difference() method will return a new set, that contains only the
elements that are NOT present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow
duplicates.

Department of CS&IT, S.S.D.M College. 32


Python: Unit - II

Dictionaries are ordered from python 3.7 version, in earlier versions Dictionaries are
unordered
Dictionaries are written with curly brackets, and have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

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

Ordered or Unordered?
The dictionaries are ordered, it means that the items have a defined order, and that order
will not change.
Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key.

Department of CS&IT, S.S.D.M College. 33


Python: Unit - II

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Duplicate values will overwrite existing values

Dictionary Length
To determine how many items a dictionary has, use the len() function
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
}
print(len(thisdict))

Dictionary Items - Data Types


The values in dictionary items can be of any data type.
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

Python – Access Items


Access the items of a dictionary by referring to its key name, inside square brackets.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

Department of CS&IT, S.S.D.M College. 34


Python: Unit - II

}
x = thisdict["model"]

There is also a method called get() that will give you the same result
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)

Get Keys
The keys() method will return a list of all the keys in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change

Department of CS&IT, S.S.D.M College. 35


Python: Unit - II

Get Values
The values() method will return a list of all the values in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change

Add a new item to the original dictionary, and see that the values list gets updated as
well.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change

Department of CS&IT, S.S.D.M College. 36


Python: Unit - II

Get Items
The items() method will return each item in a dictionary, as tuples in a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)

The returned list is a view of the items of the dictionary, meaning that any changes done
to the dictionary will be reflected in the items list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change

Add a new item to the original dictionary, and see that the items list gets updated as
well
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change

Department of CS&IT, S.S.D.M College. 37


Python: Unit - II

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Python - Change Dictionary Items


Change Values
Change the value of a specific item by referring to its key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value
to it

Department of CS&IT, S.S.D.M College. 38


Python: Unit - II

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary
The update() method will update the dictionary with the items from a given argument.
If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

Python – Remove Dictionary Items


Several methods to remove items from a dictionary, pop(), popitem(), del, clear().

pop()
The pop() method removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Department of CS&IT, S.S.D.M College. 39


Python: Unit - II

popitem()
The popitem() method removes the last inserted item. (in versions before 3.7, a random
item is removed instead)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

del
The del keyword removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

The del keyword can also delete the dictionary completely.


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Department of CS&IT, S.S.D.M College. 40


Python: Unit - II

clear()
The clear() method empties the dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Loop Dictionaries
Loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.
Print all key names in the dictionary, one by one
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)

Print all values in the dictionary, one by one


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])

Also use the values() method to return values of a dictionary

Department of CS&IT, S.S.D.M College. 41


Python: Unit - II

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Use the keys() method to return the keys of a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)

Loop through both keys and values, by using the items() method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x,y in thisdict.items():
print(x, y)

Copy Dictionary
A dictionary simply cannot copy by typing dict2 = dict1, because: dict2 will only be a
reference to dict1, and changes made in dict1 will automatically also be made in. dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

Department of CS&IT, S.S.D.M College. 42


Python: Unit - II

}
mydict = thisdict.copy()
print(mydict)

Another way to make a copy is to use the built-in function dict().


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Or, create three dictionaries, then create one dictionary that will contain the other three
dictionaries
child1 = {
"name" : "Emil",

Department of CS&IT, S.S.D.M College. 43


Python: Unit - II

"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

Department of CS&IT, S.S.D.M College. 44

You might also like