0% found this document useful (0 votes)
136 views110 pages

Unit 3 PPTs

Uploaded by

rajputaditi2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views110 pages

Unit 3 PPTs

Uploaded by

rajputaditi2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 110

Lists in Python:

• In python, A list is sequence of values called items or elements. The elements can be any type..
• A sequence is an object that holds multiple items of data, stored one after
the other.
• So A list is a sequence object that contains multiple data items.
• We use square bracket[ ] to represent a list.

Properties:
1. Lists are mutable, which means that their contents can be changed
during a program’s execution
2. Lists are dynamic data structures, meaning that items may be added to
them or removed from them
3. You can use indexing, slicing, and various methods to work with lists in a program.
Creating List
• A list Class defines lists. A programmer can use a list’s
Constructor to create list or [] syntax.
a. Create a empty list L1=list(); or L1=[]

b. Create a list with any three integer elements L2= list([10,20,30]) or L2= [10,20,30]

c. Create a list with three string elements

L3 = list( [“Apple” , ”banana” , ”grapes” ]) or

L3= [ “Apple” , ”banana” , ”grapes” ]

d. Create a list using inbuilt range function L4=list(range(0,6))

e. Create a list using character of string

L5= list(“xyz”)
Python - Lists

• The list is a most versatile data type available in Python, which can be written as a list of comma-
separated values (items) between square brackets.
• Good thing about a list that items in a list need not all have the same type:
• Creating a list is as simple as putting different comma-separated values of
different types. For example:

list1 = ['physics', 'chemistry', 1997, 2000]


list2 = [1, 2, 3, 4, 5 ]

list3 = ["a", "b", "c", "d"]

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Accessing Values in Lists:

• To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
This will produce following result: list1[0]: physics list2[1:5]: [2, 3, 4, 5]

Negative List Indices

The negative Index access the elements from the end of a list counting in backward direction. The
index of the last element of any non empty list is always -1.
>>>list1=[10,20,30,40,50,60]
>>>list1[-1] will give 60
>>>list1[-2] will give 50
>>>list1[-3] will give 40
>>> list1[-6] will give 10
A Quick Question?

• numbers = list(range(1, 10, 2)) Quick Answer:?

OUTPUT: [1,3,5,7,9]

List Slicing

A slicing expression selects a range of elements from a sequences


• A slice is a span of items that are taken from a sequence. When you take a slice from a list, you get
a span of elements from within the list.
• To get a slice of a list, you write an expression in the following general format:
list_name[start : end]
• In the general format, start is the index of the first element in the slice, and end is the index marking
the end of the slice.
• The expression returns a list containing a copy of the elements from start up to (but not including)
end.
• days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday']
• mid_days = days[2:5]
['Tuesday', 'Wednesday', 'Thursday']

Slicing examples

• If numbers = [1, 2, 3, 4, 5]
• 2>>> print(numbers)  [1, 2, 3, 4, 5]
• >>> print(numbers[2:]) [3, 4, 5]
• >>> print(numbers[:]) [1, 2, 3, 4, 5]
• If numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• >>> print(numbers[1:8:2])  [2, 4, 6, 8]
• >>> print(numbers[-5:])[6, 7, 8, 9, 10]
Slicing:

• Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description


L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from
the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Checkpoint

• What will the following code display? numbers = [1, 2, 3, 4, 5]


my_list = numbers[:1]
print(my_list)
output:[1]

 FindList=[10,20,30,40,50]
print(FindList[:3])

print(FindList[::-1])
print(FindList[-1:0:-1])
OUTPUT—
[10, 20, 30]

[50, 40, 30, 20, 10]


[50, 40, 30, 20]
Repetition

The * symbol multiplies two numbers. However, when the operand on the left side of the * symbol is a
sequence (such as a list) and the operand on the right side is an integer, it becomes the repetition
operator.

1. >>> numbers = [0] * 5


>>> print(numbers) [0, 0, 0, 0, 0]
2. l1=list(“InfyTq”)
then l1*3 will be

output: [InfyTqInfyTqInfyTq]

Delete List Elements:

• To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know. Remove method will ask
for value to be deleted.
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
del list1[2];
print ("After deleting index 2 : “)
print (list1)
• This will produce following result:
After deleting value at index 2 :
['physics', 'chemistry', 2000]
>>>list1.remove('physics')
>>> list1 ['chemistry', 2000]

Del Examples
• >>> MyList=[10,20,30,40,50,60]
• >>> MyList
• [10, 20, 30, 40, 50, 60]
• >>> del MyList[1]
• >>> MyList
• [10, 30, 40, 50, 60]
• >>> del MyList[-1]
• >>> MyList
• [10, 30, 40, 50]
• >>> del MyList[1:3]
• >>> MyList
• [10, 50]
Finding length of List

• Python has a built-in function named len that returns the length of a sequence, such as a
list. The following code demonstrates:
my_list = [10, 20, 30, 40] size = len(my_list) print(size) will give 4
• The first statement assigns the list [10, 20, 30, 40] to the my_list variable.
• The second statement calls the len function, passing the my_list variable as an argument

CONCATENATION

+ will act as concatenation for List

• >>>a=[2, 56]
• >>> b=["anj","d"]
• >>> a+b
• [2, 56, 'anj', 'd']
Membership test

• in operations can be applied to test the whether an element is part of list or not.

>>> 'Sanjeev' in ['sonu', 'rajiv', 'Sanjeev'] True

Basic List Operations: SUMMARY

• Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.
• In fact, lists respond to all of the general sequence operations we used on strings
in the prior chapter :
Python Expression Results Description
([1, 2, 3]) Length

2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

i!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

n [1, 2, 3] TRUE Membership


1. Write a
x in [1, 2, 3]: print x, 23 Iteration
python

program to read sales of five days in list using loop

• A=[]
• For i in range(5):
A[i]= int(Input(“Enter the sale”))

2. Write a python program to read sales of five days in list using loop

• sales = [0] * NUM_DAYS


• index = 0

• print('Enter the sales for each day.')

• while index < NUM_DAYS:

• print('Day #', index + 1, ': ', sep='', end='')

• sales[index] = float(input())

• index += 1

• print('Here are the values you entered:')

• for value in sales:

• print(value)
Expected output
Checkpoint Question

• What will the following code display?

numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
numbers2 += numbers1
print(numbers1)
print(numbers2)
OUTPUT:[1,2,3]
[10,20,30,1,2,3]

List can be concatenated through += operations with string but not .


In this case each character of string becomes member in combined list.
 num=[1,2,3,4]
 num+="hello"
 print(num) [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o']
 l=num+”hello”
 print(l) ERROR!
Traceback (most recent call last):
File "<main.py>", line 12, in <module>
TypeError: can only concatenate list (not "str") to list

 a=['a','b','c']

 a+="hello"
 print(a) ['a', 'b', 'c', 'h', 'e', 'l', 'l', 'o']
 b=a+"hello"
 print(b) ERROR!
Traceback (most recent call last):
File "<main.py>", line 12, in <module>
TypeError: can only concatenate list (not "str") to list

Copying list

Recall that in Python, assigning one variable to another variable simply makes both variables reference
the same object in memory.
• For example, look at the following code:
• list1 = [1, 2, 3, 4]
• list2 = list1
• After this code executes, both variables list1 and list2 will reference the same list in memory.
Copied Lists refers to same object

• To demonstrate this,
• >>> list1 = [1, 2, 3, 4]
• >>> list2 = list1
• >>> print(list1)
• [1, 2, 3, 4]
• >>> print(list2)
• [1, 2, 3, 4]
• >>> list1[0] = 99
• >>> print(list1)
• [99, 2, 3, 4]
• >>> print(list2)
• ?????????
Creating different but identical lists
• Suppose you wish to make a copy of the list, so that list1 and list2 reference two separate but
identical lists.
• One way to do this is with a loop that copies each element of the list. Here is an example:
• # Create a list with values.
• list1 = [1, 2, 3, 4]
• # Create an empty list.
• list2 = []
• # Copy the elements of list1 to list2.
• for item in list1:
• list2.append(item) OR we can use :
• list1 = [1, 2, 3, 4]
• list2 = [] + list1
Using built in methods
 List1=[“red”,”blue”,”pink”]
• List2=List1.copy() # will copy list1 to list2
>>>list2 will give [“red”,”blue”,”pink”]
Or we can use List2=list1[:]

PYTHON INBUILT FUNCTIONS FOR

LISTS

• len( )—returns number of items in the list


• max( )—return item with maximum value
• min( )—return item with minimum value
• sum( )—return sum of all items in the list
• random.shuffle( )—shuffle items randomly

Examples

MyList=[10,20,30,40,50]
print(MyList) print(len(MyList)) print(max(MyList)) print(min(MyList)) print(sum(MyList))

import random
random.shuffle(MyList) # will the shuffle in the original list
print(MyList) OUTPUT—
[10, 20, 30, 40, 50]
5
50
10
150
[40, 30, 20, 50, 10]

What if we want original list and shuffle list also.


list1 = list(range(5))
print(list1)
import random
list1_new = random.sample(list1, len(list1))
print(list1_new)

OUTPUT— [0, 1, 2, 3, 4]
[1, 4, 3, 2, 0]
List Methods in python

Lists have numerous methods that allow you to work with the elements that they contain. Python
provides built-in functions that are useful for working with lists.

• The append Method


The append method is commonly used to add items to a list. The item that is passed as an argument is
appended to the end of the list’s existing elements.

List.append()

This method adds an item to the end of the list. MyList = ["apple", "banana", "cherry"]
MyList.append("orange")

print(MyList)

OUTPUT—
['apple', 'banana', 'cherry', 'orange']
Example : Append()
insert( ) method

• This method adds an item Before the specified index of the list. The insert method allows you to
insert an item into a list at a specific position.
• You pass two arguments to the insert method: an index specifying where the item should be
inserted and the item that you want to insert

MyList = ["apple", "banana", "cherry"] MyList.insert(2, "orange") print(MyList)

OUTPUT—
['apple', 'banana', 'orange', 'cherry']

The remove Method

• The remove method removes an item from the list.


• You pass an item to the method as an argument and the first element containing that item is
removed.

• This reduces the size of the list by one element.


• All of the elements after the removed element are shifted one position toward the beginning of
the list.
• A Value Error exception is raised if the item is not found in the list.
Example: Remove method

• list1 = ['P’, 'B', 'C']

• print('Here are the items in the food list:')

• print(list1)

• item = input('Which item should I remove? ‘)

• list1.remove(item)

• print('Here is the revised list:')

• print(list1)
Here are the items in the food list:
• ['P', 'B', 'C']

• Which item should I remove? B

• Here is the revised list:

• ['P', 'C']
pop( ) method #with or without parameter

• This method removes the specified index from the list.


• If index is not specified, then it removes the last item from the list.

• MyList = ['apple', 'banana', 'cherry']


• MyList.pop( )
• print(MyList)

• OUTPUT—
• ['apple', 'banana']
Pop with parameter

• MyList = ['apple', 'banana', 'cherry']


• MyList.pop(1)
• print(MyList)

• OUTPUT—['apple', 'cherry']
clear( ) method

• This method removes all items from the list.


• MyList = ['apple', 'banana', 'cherry']
• MyList.clear()
• print(MyList)

• OUTPUT—[ ]

extend( ) method

This method adds one list at the end of another list. list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list1.extend(list2) print(list1)

OUTPUT—['a', 'b', 'c', 1, 2, 3]


count( ) method

This method counts the occurrence of an item in the list.

MyList = ['A','B','C','A','B','C']
print(MyList.count('A'))

OUTPUT— 2
Index method
• Earlier you saw how the ‘in operator’ can be used to determine whether an item is in a list.
• Sometimes you need to know not only whether an item is in a list, but where it is located. The
index method is useful in these cases. You pass an argument to the index method and
• it returns the index of the first element in the list containing that item. If the item is not found in
the list, the method raises a Value Error exception.
Example program: index
reverse( ) method

This method reverses the items of the list. MyList = ['A','B','C','D','E','F']

MyList.reverse( ) print(MyList)

OUTPUT—['F', 'E', 'D', 'C', 'B', 'A']

The sort Method

The sort method rearranges the elements of a list so they appear in ascending order (from the lowest
value to the highest value).

>>>my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]

>>>print('Original order:', my_list)

>>>my_list.sort()
>>>print('Sorted order:', my_list) Output:

• Original order: [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]

• Sorted order: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Sort : Other example

>>>my_list = ['beta', 'alpha', 'delta', 'gamma']


>>>print('Original order:', my_list)
>>>my_list.sort()
>>>print('Sorted order:', my_list)
When this code runs it will display the following:
• Original order: ['beta', 'alpha', 'delta', 'gamma']
• Sorted order: ['alpha', 'beta', 'delta', 'gamma']

Sorting in reverse

But if we want to sort the elements of the list into descending order, then we must mention

‘reverse=True’ in the sort( ) method.

x. sort(reverse=True) Example—

MyList = ['D','B','A','F','E','C']
MyList.sort(reverse=True) print(MyList)

OUTPUT—['F', 'E', 'D', 'C', 'B', 'A']


How to convert String to List of Characters
str="Python"
print(str) MyList=list(str)
print(MyList)

Output—Python
['P', 'y', 't', 'h', 'o', 'n']
Here the list( ) function breaks a string into individual letters.

Question

• Consider the list. Write a Python program to retrieve only the first letter of each word from the
given list.
• words=['Apple','Banana','Orange','Cherry']
Solution

• words=['Apple','Banana','Orange','Cherry']
• MyList=[ ]
• for w in words:
• MyList.append(w[0])
• print(MyList)

• OUTPUT—['A', 'B', 'O', 'C']
Checkpoint questions

• del vs remove method?

• How do you find the lowest and highest values in a list?

• Assume the following statement appears in a program:

names = []
Which of the following statements would you use to add the string ‘python’ to the list at
index 0? Why would you select this statement instead of the other?
a. names[0] = ‘python'
b. names.append(‘python')
 Write a python function which accepts a list as an argument and returns the sum of the list’s
elements.

• def get_total(value_list):
• total = 0
• for num in value_list:
• total += num
• return total

• numbers = [2, 4, 6, 8, 10]


• print('The total is', get_total(numbers))
Quiz questions

my_list=[‘two’,5,[‘one’,2]]

print(len(my_list) 3

Mix_list=[‘pet’,’dog’,5,’cat’, ’good’,’dog’]
Mix_list.count(‘dog’) 2

mylist=[‘red’,3]
mylist.extend(‘green’)
Print(len(mylist))

3
Some List Based Questions for Practice

• Using the list L, what is the value of each of the expressions (a) through (e) below?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']

(a) len(L)
(b) len(L[1])
(c) L[2] Toyota
(d) L[4] + '***'
(e) L[1] == L[2]
• Using the list L, what is the value of each of the expressions (a) through (e) below?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']

(a) len(L)
(b) len(L[1])
(c) L[2] Toyota
(d) L[4] + '***'
(e) L[1] == L[2]
• >>> L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
• >>> len(L)
• 5
• >>> len(L[1])
• 9
• >>> L[2]Toyota
• SyntaxError: invalid syntax
• >>> L[4] + '***'
• 'Tesla***'
• >>> L[1] == L[2]
• False
• >>>
Question

• Using the list defined below, what does Python print when these statements are executed?
L = ['Ford', 'Chevrolet', 'Toyota', 'Nissan', 'Tesla']
(a)for x in L:
print('Item:', x)
(b) size = len(L)
for i in range(size):
print(i+1, L[i])
print("Total count:", size)

• Item: Ford
• Item: Chevrolet
• Item: Toyota
• Item: Nissan
• Item: Tesla
• 1 Ford
• Total count: 5
• 2 Chevrolet
• Total count: 5
• 3 Toyota
• Total count: 5
• 4 Nissan
• Total count: 5
• 5 Tesla
• Total count: 5

• Write a program to search an element in a list Linear search

def linear_search(My_list,key):
for i in range(len(My_list)):
if My_list[i]==key:
return i
return -1
My_list=[1,5,6,10,15,45,67]
result=linear_search(My_list,32)
if(result!=-1):
print("Element found at position",result)
else:
print("Element not found")
stack = []

Stack using List


# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)
# pop() fucntion to pop # element
from stack in # LIFO order
print('\nElements poped from
stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are


poped:')
print(stack)
Queue Using List
• Program to perform binary search in a list
def binary_search(My_list,key):
low=0
high=len(My_list)-1
while low<=high:
mid=(low+high)//2
print(My_list[mid])

if My_list[mid]==key:
return mid
elif key>My_list[mid]:
low=mid+1
else:
high=mid-1
return -1
My_list=[10,20,56,516,3576,34324,3245213]
result=binary_search(My_list,34324)
if(result!=-1):
print("Element found at position",result)
else:
print("Element not found")
List Comprehensions

List comprehensions represent creation of new lists from an iterable object(such as list, set, tuple,
dictionary) that satisfy a given condition.

List comprehension contains very less code usually one line to perform a task.

• [exp for val in collection]

• [expr for val in collection if<test>]

• [expr for val in collection if<test1> and <test2>]

• [expr for val1 in collection1 and val in collection2]]

Squares=[]
for i in range(1,101): squares.append(i**2)

OR
Squares=[i**2 for i in range(1,101)] Print(square)
……………………………………………………………

d=[i*3 for i in range(23) if i%2==0]


Questions on Comprehensions

• Q1. Create a list having numbers [1,4,7,10,.....100] as its elements using list comprehension
method.
• Q2. WAP to generate a list of 10 starting multiple of 5 using list comprehension method

Q3. Write list comprehension to generate [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] this list

• 1
mylist = [x+3 for x in range(-2,98,3)]
print(mylist)
Or b=[3*i-2 for i in range(1,35)]
• 2
mylist = [x*5 for x in range (1, 11)] print(mylist)

• 3
num_list = [x for x in range(100) if x % 10 == 0]
print(num_list)
• OR a=[i*10 for i in range(0,10)]
Other Examples

num = ["Even" if i%2==0 else "Odd" for i in range(10)] print(num)


Output:

['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']

Extract the vowels using comprehension

line=‘ This is python programming language class’

Vowels= [s for s in line if s in “aeiou”]


Tuple in Python

CREATING TUPLES

We create a tuple by writing elements separated by commas inside parenthesis ( ).


Example—
T1= ( ) #empty tuple# type is tuple T=(4) #not a tuple but int
T2 = (10,) #tuple with one element
T3 = (12, 20.5, ‘Delhi’, ‘UP’)
T4 = (10, 20, 30, 40)

Examples

• Note:
• >>> T1=()
• >>> type(T1)
• <class 'tuple'>
• >>> T2=(10,)
• >>> type(T2)
• <class 'tuple'>
• >>> T3=(10)
• >>> type(T3)
• <class 'int'>
• >>> T4=10,20,30,40
• >>> type(T4)
• <class 'tuple'>

• So a single value in parenthesis is not a tuple.

Changing a Tuple

Unlike lists, tuples are immutable data type.


This means that the items of a tuple cannot be changed once it has been created. But, if the item is
itself a mutable data type like list, its nested items can be changed.
Example—

Tup = (1, 2, 3, [4, 5])


#Tup[2] = 6
#Error:'tuple' object does not support
item assignment
Tup[3][1] = 8
print(Tup)
OUTPUT—
(1, 2, 3, [4, 8])
THE tuple( ) FUNCTION for type casting

It is used to convert string or lists into tuple. Example—

Tup1=tuple("PYTHON")
print(Tup1)

OUTPUT—
('P', 'Y', 'T', 'H', 'O', 'N')

Example—

Tup2=tuple([1,2,3]) print(Tup2)

OUTPUT— (1, 2, 3)

FUNCTIONS FOR TUPLE

1. len( )
2. max( )
3. min( )
4. sum( )
5. index( )
6. count( )
Example—

codes Output
Tup1=(1,2,3,3,4,5,2) OUTPUT—

1. print(Tup1) 1. (1, 2, 3, 3, 4, 5, 2)
2. 7
2. print(len(Tup1)) 3. 5
3. print(max(Tup1)) 4. 1
5. 1
4. print(min(Tup1))
6.2
5. print(Tup1.index(2))

6. print(Tup1.count(3))
Tuple Examples

Tup2=tuple("CORE PYTHON")
OUTPUT—
1. print(Tup2)
1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')
2. print(len(Tup2))
2. 11
3. print(max(Tup2))
3. Y
4. print(min(Tup2))
4.
5. print(Tup2.index('H')) 5. 8
6. 2
6. print(Tup2.count('O'))
INDEXING & SLICING IN TUPLE

Tup2=tuple("CORE PYTHON") OUTPUT—

1. print(Tup2) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')

2. print(Tup2[0]) 2. C

3. print(Tup2[5]) 3. P

4. print(Tup2[-5]) 4. Y

5. print(Tup2[-7]) 5.
6. print(Tup2[-1]) 6. N
Example—

(Indexing and slicing)

Tup=tuple("CORE PYTHON") Output

1. print(Tup) 1. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')

2. print(Tup[0:4]) 2. ('C', 'O', 'R', 'E')

3. print(Tup[6:]) 3. ('Y', 'T', 'H', 'O', 'N')

4. print(Tup[0:]) 4. ('C', 'O', 'R', 'E', ' ', 'P', 'Y', 'T', 'H', 'O', 'N')

5. print(Tup[-1::-1]) 5. ('N', 'O', 'H', 'T', 'Y', 'P', ' ', 'E', 'R', 'O', 'C')
OPERATORS IN TUPLE

• + Operator
• * Operator

The + Operator
It is the concatenation operator that is used to join two tuples.

Example—
Tup1=(1,2,3)
Tup2=(4,5,6)
Tup3=Tup1 + Tup2 print(Tup3)

OUTPUT—
(1, 2, 3, 4, 5, 6)
The * Operator

• It is the repetition operator that is used to repeat or replicate the items of a tuple.

Example— Tup=(1,2,3)
Tup2=Tup * 2
print(Tup2) OUTPUT—
(1, 2, 3, 1, 2, 3)

How to sort elements in Tuple

Let Tup=(1,4,2,5,3) be a tuple. Different ways to sort this tuple.

Method1—
Convert given tuple to list and then apply sort( ) method.

Example—
Tup=(1,4,2,5,3)
print(Tup)
List1=list(Tup)
List1.sort()
Tup1=tuple(List1)
print(Tup1)
OUTPUT— (1, 4, 2, 5, 3)
(1, 2, 3, 4, 5)

Method2—

Using sorted( ) method.


Syntax is sorted( Iterable, reverse=True)

Here Iterable is the tuple name


To sort in descending order, write reverse=True

Example:
Tup=(1,4,2,5,3)
print(sorted(Tup))

OUTPUT—
[1, 2, 3, 4, 5]
Sorting Examples

Example: Tup=tuple("PYTHON") print(sorted(Tup))

OUTPUT—
['H', 'N', 'O', 'P', 'T', 'Y']

Example— Tup=tuple("PYTHON") print(sorted(Tup,reverse=True))

OUTPUT—
['Y', 'T', 'P', 'O', 'N', 'H']
Deleting a Tuple

• We cannot change the items in a tuple. Also we cannot delete or remove items from a tuple.
• But deleting a tuple entirely is possible using the keyword del.
• Example—
Tup_new = ('p','y','t','h','o','n')
print(Tup_new) #('p', 'y', 't', 'h', 'o', 'n')

del Tup_new[3] # TypeError: 'tuple' object doesn't support item deletion

del Tup_new # to delete an entire tuple


print(Tup_new) # NameError: name 'Tup_new' is not defined

Membership Operator in Tuple


We can test if an item exists in a tuple or
not, using the 4. print('n' not in Tup_new)
keyword in and not in.

Tup_new = ('p','y','t','h','o','n')

1. print(Tup_new)

2. print('p' in Tup_new)

3. print('e' in Tup_new)
OUTPUT—

1. ('p', 'y', 't', 'h', 'o', 'n')

2. True

3. False

4. False
Tuples are more efficient

• Since Python does not have to build tuple structures to be modifiable, they are simpler and more
efficient in terms of memory use and performance than lists

• So in our program when we are making “temporary variables” we prefer tuples over lists

• import sys

• List1=[1,2,3,4]

• Tuple1=(1,2,3,4)

• print("List size", sys.getsizeof(List1))

• print("Tuple size", sys.getsizeof(Tuple1)) 96,80


• Unpacking a Tuple
• 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":
• Example
• Unpacking a tuple:
• fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
• Note: The number of variables must match the
number of values in the tuple, if not, you must use an
asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable name
and the
values will be assigned to the variable as a list:

Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

If the asterisk 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.

Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)
Updating Tuples:

• Tuples are immutable which means you cannot update them or change values of tuple elements.
But we able able to take portions of an existing tuples to create a new tuples as follows:
• Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz'); tup3 = tup1 + tup2; print tup3;
This will produce following result:
(12, 34.56, 'abc', 'xyz')

Basic Tuples Operations:

• Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.
• In fact, tuples respond to all of the general sequence operations we used on strings in the prior
chapter :

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!‘) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) TRUE Membership
for x in (1, 2, 3): 123 Iteration
print x,

Tuple vs List

• Declared with () • Declared with []


• Immutable • Mutable
• Faster • Slower
• Less memory required • More memory usage
• Limited method • Many methods
• Tuples can be dictionary keys. • Lists cannot be dictionary keys.
• Efficient for temporary variables or fixed • Efficient for dynamic data
data
• Data can be more secured
• Data is less secure
• tuple1 = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• tinytuple = (123, 'john')
• print(tuple1+tinytuple)

#('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Dictionaries in Python

• A dictionary represents a group of items/elements arranged in the form of key : value pair.
• In Dictionary, the first element is the key and second element is the value associated with the
corresponding key.
• All the elements are enclosed within the curly braces{ }.
• Example—

• dict = {1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’}

• Dictionary key value


Creating Dictionary

# Creating Dictionary with Integer Keys

Dict = {1: ‘python', 2: ‘Program', 3: ‘example'} print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary with Mixed keys Dict = {'Name': ‘Python', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
dict( ) function to create a dictionary in Python

• Dictionary can also be created with the help of the built-in function dict( ). An empty
dictionary can also be created by using curly braces{ }.

• # Creating an empty Dictionary

• Dict = {}
print("This is an empty Dictionary: ")
print(Dict)
Accessing Values in Dictionary:

• To access dictionary elements, you use the familiar square brackets along with the key to obtain
its value:
• Example:

• This will produce following result: dict['Name']: Zara dict['Age']: 7

• If we attempt to access a data item with a key which is not part of the dictionary, we get an error
as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
• This will produce following result:
dict['Zara']:
Traceback (most recent call last): File "test.py", line 4, in
<module> print "dict['Alice']: ", dict['Alice']; KeyError: 'Alice'

Updating Dictionary:

• You can update a dictionary by adding a new entry or item (i.e., a key- value pair), modifying an
existing entry, or deleting an existing entry as shown below:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry dict['School'] = "DPS
School"; # Add new entry print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

This will produce following result: dict['Age']: 8 dict['School']: DPS School

Delete Dictionary Elements:

• You can either remove individual dictionary elements or clear the entire contents of a dictionary. You
can also delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the del statement:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key
'Name' d
dict.clear(); # remove all entries in dict del dict ; # delete entire
dictionary

• Note: del() method is discussed in subsequent section.

Properties of Dictionary Keys:

• Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys:
• (a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins.
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
• This will produce following result:
dict['Name']: Manni

• (b) Keys must be immutable. Which means you can use strings, numbers, or tuples as
dictionary keys but something like ['key'] is not allowed.
• Example:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
• This will produce following result. Note an exception raised:
Traceback (most recent call last):
File "test.py", line 3, in <module> dict = {['Name']: 'Zara',
'Age': 7};
TypeError: list objects are unhashable
Built-in General Functions applicable on Dictionary:

SN Function with Description


1 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
2 str(dict)
Produces a printable string representation of a dictionary
3 type(variable)
Returns the type of the passed variable. If passed variable is dictionary
then it would return a dictionary type.
Inbuilt Methods
From Key Function

• x = ('key1', 'key2', 'key3’)


• y=0
• thisdict = dict.fromkeys(x, y)
• print(thisdict)

Output: {‘key1’:0,’key2’:0,’key3’:0}

dict.clear()

• D.clear() -> None. Remove all items from D.


d.copy

• D.copy() -> Returns a copy of D


dict.get(key)

• D.get(k) -> D[k] if k in D, else returns None(By default, else can be sent as parameter while calling

dict.items(), dict.keys(), dict.values()

Returns corresponding list


d.update()

• The update() method updates the dictionary with the elements from the another dictionary object
or from an iterable of key/value pairs.
• The update() method takes either a dictionary or an iterable object of key/value pairs (generally
tuples).
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.update({"color": "White"})

print(car)
OUTPUT:{“brand”:”Ford”,”model”:”Mustang”,”year”:1964,”color”:”White”}

Pop and popitem()


 The pop() method removes and returns an element from a dictionary corresponding to the given key.
• The popitem() returns and removes an arbitrary(LIFO) element (key, value) tuple pair from the dictionary.
Does not take any argument.
EXAMPLE:
Setdefault()

• The set default() method returns the value of a key (if the key is in dictionary). If not, it inserts
key with a value to the dictionary.

Return Value from set default()


• The set default() returns:
• value of the key if it is in the dictionary
• None: if key is not in the dictionary and default value is not specified
• Specified default_value if key is not in the dictionary
• Key and correponding value if specified is added in dictionary and mentioned value is returned
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.setdefault("model", "Bronco")

print(x)
Set default example
Iteration through dictionary:

>>> Grades={"Tammana":"A","Pranav":"B","Sumit":"C"}
>>> for key in Grades: print(key,":",str(Grades[key]))

Tammana : A Sumit : C Pranav : B

Nested Dictionaries
Traversing Nested Dictionaries
Sorting Dictionary

• You can obtain a sorted list of the keys using the sorted() function.
>>>prices = {'Apple': 1.99, 'Banana': 0.99, 'Orange': 1.49, 'Cantaloupe': 3.99, 'Grapes': 0.39}
>>>sorted(prices)
['Apple', 'Banana', 'Cantaloupe', 'Grapes', 'Orange'] Can be applied on tuples as well.

Write a function histogram that takes string as parameter and generates a frequency of character
contained in it.
(Hint: Use Dictionary to store character as key and count as value in dictionary. Initially you can take
empty dictionary)

Solution

S=“AAPPLE”
D=dict()
for C in S:
if C not in D:
D[C]=1
else:
D[C]=D[C]+1
print(D)
output-{‘A’:2,’P’:2,’L’:1,’E’:1}

Write a program to print and store squares of upto n numbers in the dictionary

• {1:1,2:4,3:9…….n:n2}

• def sq_of_numbers(n):

• d=dict()

• for i in range(1,n+1):

• if i not in d:

• d[i]=i*i

• return d
• print("sqaures of numbers:")

• Z=sq_of_numbers(5)

• print(Z)

Describe what the following statements do and write their output.

If lt = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]

lt=dict(lt)

print(lt)

lt.clear()

print(lt)

output-{'a': 'b', 'e': 'f', 'c': 'd'}


{}
More on dictionary
Note that
my_dict = {4:'e', 3: 'd', 2: 'c', 1: 'b', 0:
'a'} Indexing is not applicable in
print(my_dict) dictionary. Here 0, 4 represent
print(my_dict[0]) the key 0 and key 4 respectively.
print(my_dict[4]) Slicing is also not applicable in dictionary.
Therefore,
#print(my_dict[-1]) print(my_dict[-1]) gives KeyError:
#print(my_dict[0:2])
-1
OUTPUT— print(my_dict[0:2]) gives TypeError: unhashable
type: 'slice'
{4: 'e', 3: 'd', 2: 'c', 1: 'b', 0: 'a'}
ae
Q1 Find the output?

my_dict = {'a': 10, 'b': 20, 'c': 30}

1. print(my_dict.get('c'))

2. print(my_dict.get('d'))

3. print(my_dict.get('d',-1))
OUTPUT—

1. 30

2. None

3. -1
my_dict = {'a': 10, 'b': 20, 'c': 30}

1. print(my_dict.pop('b'))

2. print(my_dict.pop('z'))

3. print(my_dict.pop('z', -1))

4. print(my_dict)

output

1. 20

2. Key Error

3. -1

4. {'a': 10, 'c': 30}


• Write a Python program to sum all values of the items in a dictionary.
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))

OUTPUT— 293

SETS IN PYTHON

• A set in Python is an unordered collection of unique elements without duplicate elements in the
set.

• Unlike Tuple, Set is Mutable means that once it created, we can change its contents.

• This data type support mathematical set operations.


How to create a set
As Set is created by enclosing all elements with a curly braces { } and separated by commas.
It can have any number of items and that can be of different types (integer,
float, tuple, string etc.).

Note: A set cannot have a mutable element, like list, set or dictionary, as its element.
Example—
set1 = {1, 2, 3, 4, 5}
print(set1)

set2 = {5, "Python", (1, 2, 3, 4, 5)}


print(set2)

OUTPUT—
{1, 2, 3, 4, 5}
{'Python', (1, 2, 3, 4, 5), 5}
Example

set3 = {1, 2, 3, 4, 5, 3, 2, 5}
print(set3)

Output—
{1, 2, 3, 4, 5}

Example—

set4 = {1, 2, 3,[4, 5]}


print(set4)

OUTPUT—
TypeError: unhashable type: 'list'
Example—

1. set5 = {1, 2, 3,{4, 5}}

2. print(set5)

OUTPUT—

Type Error: unhashable type: 'set'

Note: An empty curly braces { } will make an empty dictionary in Python.


To make a set without any elements we use the set( ) function without any argument.

Convert List to Set and Tuple to Set

Example—

My_list=[1,2,3,4,5] print(My_list)

My_set=set(My_list) print(My_set)

OUTPUT—
[1, 2, 3, 4, 5]
{1, 2, 3, 4, 5}

Example—

My_tuple=(1,2,3,4,5) print(My_tuple)

My_set=set(My_tuple) print(My_set)

OUTPUT— (1, 2, 3, 4, 5)

{1, 2, 3, 4, 5}

METHODS IN SETS

• add( )

• remove( )

• clear( )

• issubset( )

• issuperset( )

• union( )
• intersection( )

• difference( )

• symmetric_difference( )

add( element)
Add the element into the set.
Example—

set1={1,2,3,4,5}
print(set1)

set1.add(10) print(set1)

OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 10}
remove(element) / discard(element)

Example—

set2={1,2,3,4,5}
print(set2)

set2.remove(3) #set2.discard(3)(No error) print(set2)

OUTPUT—
{1, 2, 3, 4, 5}
{1, 2, 4, 5}
issubset( setName)

• This method checks if one set is subset of another set or not.


• It give output in Boolean i,e. True or False
• Example—

1. s1={10,20,30,40}
2. s2={10,20,30,40,50}
3. print(s1.issubset(s2))
OUTPUT—

True
clear( )

Remove all elements from the set. Example—

set3={1,2,3,4,5}
print(set3)

set3.clear()
print(set3)

OUTPUT—

{1, 2, 3, 4, 5}
set()
issuperset( setName)

• This method checks if one set is superset of another set or not. It give output in Boolean i,e. True
or False
Example—

1. s1={10,20,30,40}

2. s2={10,20,30,40,50}

3. print(s2.issuperset(s1))

OUTPUT—
True

SET OPERATIONS

• union( )

• intersection( )
• difference( )

• symmetric_difference( )

union( ) method
The union of two sets S1 and S2 is a set of elements that are present in S1 or in S2 or in both S1 and S2.

Syntax is:
1. set1.union(set2) Symbol is:| i.e, vertical bar

Example— s1={10,20,30} s2={10,20,30,40,50}


print(s1.union(s2))

OUTPUT—
• {40, 10, 50, 20, 30}
Example—

1. s1={10,20,30}

2. s2={10,20,30,40,50}

3. s3=s1 | s2

4. print(s3)

OUTPUT—
{40, 10, 50, 20, 30}

intersection( ) method

The intersection of two sets S1 and S2 is a set of elements that are present in both S1 and S2.
Syntax is: set1.intersection(set2) Symbol is: &
• Example—

• s1={10,20,30}
• s2={10,20,30,40,50}

• print(s1.intersection(s2))

• OUTPUT—

• {10, 20, 30}

Example

1. s1={10,20,30}

2. s2={10,20,30,40,50}

3. s3=s1 & s2

4. print(s3)

OUTPUT—
• {10, 20, 30}
difference( ) method
Syntax is: set1.difference(set2) Symbol is: -
 s1={10,20,30,40,50}
 s2={30,40,50,60,70}
 print(s1.difference(s2))
 OUTPUT—
 {10, 20}

 s1={10,20,30,40,50}
 s2={30,40,50,60,70}
 s3=s1 - s2
print(s3)# will remove common element from s1
 Symmetric_difference( ) method
• The symmetric difference of two sets S1 and S2 is a set of elements that are present in either in S1
or in S2 but not in both sets.
Syntax is: set1.symmetric_difference(set2) Symbol is:^
Example—
1. s1={10,20,30,40,50}
2. s2={30,40,50,60,70}
3. print(s1.symmetric_difference(s2)) OUTPUT—
{20, 70, 10, 60}
Example using symbol

Example— s1={10,20,30,40,50}
s2={30,40,50,60,70}
s3=s1 ^ s2 print(s3)

OUTPUT—

{20, 70, 10, 60}


'difference_update()',

• >>> a={3,4,5}

• >>> b={3,4,534,4}

• >>> a-b

• {5}

• >>> a

• {3, 4, 5}

• >>> b

• {3, 4, 534}

• >>> a.difference_update(b)

• >>> a

• {5}

• >>> b

• {3, 4, 534}

• >>>
NOTE:

We cannot access items in a set by referring to an index, since sets are unordered the elements has no
index.
But we can check if a specified element is present in a set or not, by using the in keyword.

Example—
Myset = {"dell", "sony", "lenovo", "hp"} print("lenovo" in Myset)

OUTPUT—

True

How to change elements in Set



Once a set is created, we cannot change its elements, but we can add new elements.
Add Elements in Set
To add one element to a set use the add( ) method.
To add more than one element to a set use the update( ) method.

Example—
Myset = {"dell", "sony", "lenovo", "hp"} Myset.add("samsung")
print(Myset)

OUTPUT—
{'lenovo', 'sony', 'dell', 'hp', 'samsung'}

Example— Update

Myset = {"dell", "sony", "lenovo", }


Myset.update(["apple","hp","samsung"]) print(Myset)

OUTPUT—
{'apple', 'samsung', 'sony', 'dell', 'hp', 'lenovo'}

Display unique string along with length


formed by alphabetical sorting of unique symbols
• E.g. if input is ppyythonn
• Then output should be: hnopty6

Solution
• unique=set(input())
• l=list(unique)
• l.sort()
• d=""
• for i in l:
• d+=i
• print(d+str(len(d)))

You might also like