Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views25 pages

Pb-U7.3 List

This document provides an overview of Python lists, detailing their characteristics, creation, initialization, and various operations such as indexing, slicing, and using built-in functions. It explains how to manipulate lists using methods like append and extend, as well as the differences between these methods. Additionally, it covers list operators, membership operators, and examples of list slicing and modification.

Uploaded by

rvsnhis
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)
24 views25 pages

Pb-U7.3 List

This document provides an overview of Python lists, detailing their characteristics, creation, initialization, and various operations such as indexing, slicing, and using built-in functions. It explains how to manipulate lists using methods like append and extend, as well as the differences between these methods. Additionally, it covers list operators, membership operators, and examples of list slicing and modification.

Uploaded by

rvsnhis
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/ 25

Unit 3: Advance Python Vision 2 Win

LIST
 Introduction :
o LIST is a collection of items and each item has its own index value.
o List is a standard data type of Python. It is a sequence which can store values of any kind.
o List is represented by square brackets “[ ] “
o A List is a mutable data type which means any value from the list can be changed.
o List is a sequence like a string and a tuple except that list is mutable whereas string and tuple
are immutable.
o In Python List is a sequence of items and each items can be individually access using index.
From beginning the first item in List is at index 0 and last will be at len-1. From backward
direction last item will be at index -1 and first item will be at –len.

Forward indexing
0 1 2 3 4 5 6 7 8 9 Positive Index

70 10
10 20 30 40 50 60 80 90 Values
0
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Negative Index

Backward indexing
 Creating & Initializing List:
 Creating a list
 Lists are enclosed in square brackets [ ] and each item is separated by a comma.
 Syntax: ListName = [ ]
o Creating list from existing sequences (i.e. Using list() function…
 Syntax: ListName = list(sequence)
Code: Output:
>>>Mylist = list(‘Hello’) [‘H’,’e’,’l’,’l’,’o’]
>>>Mylist
Code: Output:
>>>Mylist = (‘H’,’e’,’l’,’l’,’o’) [‘H’,’e’,’l’,’l’,’o’]
>>>Mylist = list(Mylist)
>>>Mylist

o Creating list from existing sequences (i.e. Using input() function…)


 We can also create list of single characters or single digits through input() function.
 Syntax: ListName = list(input(“Statements”))
Code: Output:
>>>Mylist = list(input(“Enter List Elements :”)) [‘1’,’2’,’3’,’4’,’5’]
Enter List Elements : 12345
>>>Mylist

Artificial Intelligence 1 Class 10


Unit 3: Advance Python Vision 2 Win

 Initializing a list
 Passing value in list while declaring list is initializing of a list.
 Syntax: ListName = [ value1, value2,…..]

o LIST can also be created Using Initialization methods…


Code: Output:
>>>Mylist = [‘H’,’e’,’l’,’l’,’o’] [‘H’,’e’,’l’,’l’,’o’]
>>>Mylist
o Ex:
 List=[]
 List=[1,2]
 List=[1,2,13.34,16.24]

 Accessing List Elements:


o First we will see the similarities between a List and a String.
o In Python, individual item of a List can be accessed by using the method of Indexing.
Index is positive address references to access item from the forward of the List & allows
negative address references to access item from the back of the List,
o While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.
o Ex: n=[10,20,30,40,50,60,70,80,90,100]

0 1 2 3 4 5 6 7 8 9
10 20 30 40 50 60 70 80 90 100
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Code: Output:
>>> n=[ 10,20,30,40,50,60,70,80,90,100]
>>>n[1] 20
>>>n[5] 60
>>>n[-3] 80
>>>n[15] Index Error
>>>n[3:8] [40,50,60,70]

 List operators
o There are many operations that can be performed with List which makes it one of the most
used data types in Python.
o Two basic operators + and * are allowed
 + is used for concatenation (joining)
 * Is used for replication (repetition)

Artificial Intelligence 2 Class 10


Unit 3: Advance Python Vision 2 Win

o List Concatenation Operator (Joining) (+):


 Joining of two or more List into a single one is called Concatenation.
 Syntax:
<List1> + <List2>
 Example:
[10,20,30] + [40,50]  [10,20,30,40,50]
[‘I’] + [“Love”] + [“India”]  [‘I’,“Love”,“India”]
Code: Output:
>>> L1=[ 10,20,30,40,50]
>>>L2=[60,70,80,90,100] [10,20,30,40,50,60,70,80,90,100]
>>>L3 = L1 + L2
>>>L3
 Note: you can only add list with another list not with int, float, complex, or string type.
[10,20,30] + 5  Invalid

o List Replication Operator (Repetition) (*):


 The * operator can be used to repeat the List for a given number of times.
 * needs two types of operands, i.e. a List and a number.
 Syntax:
<List> * <Number>
<Number> * <List>
 Example:
[10,20,30] * 3  [10,20,30,10,20,30,10,20,30]
[‘I’,“Love”,“India”] *2  [‘I’,“Love”,“India”,‘I’,“Love”,“India”]
 Note: you cannot multiply list and list using *. Only number*list or list*number is allowed.
[10,20,30] * [40,50,60]  Invalid

 Membership operators (in & not in)


o in operator: Evaluates to true if it finds a variable in the specified sequence and false
otherwise. OR Returns true if a element exist in the given list, else false.
o not in operator: Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise. OR Returns true if a element does not exist in the given list, else false.
 Syntax:
<element> in <list>
<element> not in <list>
 Example:
20 in [10,20,30,40]  True
50 in [10,20,30,40]  False
10 not in [10,20,30,40]  False
“Ind” in [“Ind”,US]  True
“e” in [‘K’,’e’,’n’,’s’,’r’,’i’]  True
“z” in [‘K’,’e’,’n’,’s’,’r’,’i’]  False

Artificial Intelligence 3 Class 10


Unit 3: Advance Python Vision 2 Win

 List Slicing
o As we know slice means “part of”, so slicing is a process of extracting part of list.
o OR Slicing is a part of a list containing some continuous character from the list.
o The list are sliced using a range of indices (List characters have their unique index position
from 0 to length-1 and -1 to –length(backward)).

o Syntax: seq = list [ start : stop ] OR seq = list [ start : stop : step ]
Where start & stop are integer, and start is staring index value, stop is ending index
value & step is stepping index.

o Example1: Lst1 = [ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 ]
Lst1[ : ] / Lst1[ : :] / Lst1  [ 10, 20, 30, 40, 50, 60, 70, 80, 90 ]
Lst1[ 2 : 5 ]  [ 30, 40, 50 ]
Lst1[ 3 : -3 ]  [ 40, 50, 60 ]
Lst1[ 0 : 10 : 2 ]  [ 10, 30, 50, 70, 90 ]
Lst1[ : : 3 ]  [ 10, 40, 70 ]
Lst1[ : : -1 ]  [ 90, 80, 70, 60, 50, 40, 30, 20, 10 ]
Lst1[ : : -2 ]  [ 90, 70, 50, 30, 10 ]
Lst1[ -4 : -1 ]  [ 60, 70, 80 ]
Lst1[ : : 3 ]  [ 10, 40, 70 ]
Lst1[ 4 ]  [ 50 ]
Lst1[ 15 ]  IndexError: list index out of range

o Example2: Lst1 = ['I','N','D','I','A']


Lst1[ 0 : 3 ]  ['I', 'N', 'D']
Lst1[ 3 : ]  ['I', 'A']
Lst1[:]  ['I', 'N', 'D', 'I', 'A']

 Use of slicing for list Modification


Code: Output:
L =["One","Two","Three"]
print(L) ['One', 'Two', 'Three']
L[0:2]=[0,1]
print(L) [0, 1, 'Three']
L[0:2]="a"
print(L) ['a', 'Three']
L[2:0]= "604"
print(L) ['a', 'Three', '6', '0', '4']
L[10:20]= "123"
print(L) ['a', 'Three', '6', '0', '4', '1', '2', '3']
L[10:20]= 456 TypeError: can only assign an

Artificial Intelligence 4 Class 10


Unit 3: Advance Python Vision 2 Win

print(L) iterable

 LIST FUNCTIONS AND METHODS


o Python offers many built-in functions for List manipulation.
o Syntax: <List_Object> . <functionName> ()

 index(substring) :
o This function returns index position of substring.
o This function is used to get the index of first matched item from the list. It returns index value
of item to search
o Syntax : <List_Object>.index(substring) :

o Example:

Code: Output:
Lst=[10,20,30,40,50,60,70,80,90,100] 4
print(Lst. index (50))
Code: Output:
Lst=[10,20,30,40,50,60,70,80,90,100] Value error: Substring not
print(Lst. index (200)) found.

 len(List) :
o This function returns the number of characters in any list including spaces.
o Syntax : len( <List_Object> )

o Example:

Code: Output:
Lst=[10,20,30,40,50,60,70,80,90,100] 10
print(len(Lst))
Code: Output:
Lst=[‘I’,’N’,’D’,’I’,’A’] 5
print(len(Lst))

INSERTING AN ELEMENT TO A LIST.


 Appending elements to a List :
o Appending means adding new items to the end of list.
o To perform this we use append () method to add single item to the end of the list.
o Syntax : <List_Object>.append(value)

o Example:

Code: Output:
Lst = [ 10, 20, 30, 40]

Artificial Intelligence 5 Class 10


Unit 3: Advance Python Vision 2 Win

Lst.append(50)
print(Lst) [10, 20, 30, 40,50]
Lst.append([60, 70])
print(Lst) [10, 20, 30, 40, 50, [60, 70]]
Lst.append(80, 90)
TypeError: append() takes
print(Lst)
exactly one argument (2 given)
Code: Output:
Lst = [‘I’,’N’,’D’,’I’,’A’] [‘I’,’N’,’D’,’I’,’A’,’Z’]
Lst.append(‘Z’)
print(Lst)
o Note: if we pass any element which is not in the list then index function will return an error.

 Updating elements of a list


o Updating is a single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator.
o Syntax : <List>[index]= (value)
o Example:

Code: Output:
Lst = [ 10, 20, 30, 40, 50 ]
Lst[2]=100
print(Lst) [10, 20, 100, 40, 50]
Lst[3]=’India’
[10, 20, 100, ‘India’, 50]
print(Lst)

 Extending elements of a list


o The extend () method adds all the elements of an iterable list to the end of the list.
o OR This function is also used for adding multiple items. With extend we can add only “list”
to any list. Single value cannot be added using extend().
o Syntax : <List>.extend(iterable)
o Example:

Code: Output:
Lst = [ 10, 20, 30]
Lst.extend([40])
print(Lst) [10, 20, 30, 40]
Lst.extend([80, 90])
[10, 20, 30, 80, 90]
print(Lst)
Lst.extend([‘a’,’b’]) [10, 20, 30, 80, 90,’a’,’b’]
print(Lst)
Code: Output:
Lst1 = [ 10, 20, 30]
Lst2 = [ 40,50]
print(Lst1) [ 10, 20, 30]
[ 40,50]

Artificial Intelligence 6 Class 10


Unit 3: Advance Python Vision 2 Win

print(Lst2)
[ 10, 20, 30, 40, 50]
Lst1.extend(Lst2)
[ 40,50]
print(Lst1)
print(Lst2)
Lst1.extend(60) TypeError: 'int' object is not
print(Lst1) iterable.

 Difference between append() & extend()


o append () allows to add only 1 items to a list, extend() can add multiple items to a list.
Exapmle: L1=[10, 20, 30, 40] L2=[80, 90]

Code: Output:
print(Lst1) [10, 20, 30, 40]
print(Lst2) [80, 90]
L1.append(50)
print(Lst1) [10, 20, 30, 40, 50]
print(Lst2) [80, 90]
L1.append(60,70) TypeError: append() takes
print(Lst1) exactly one argument (2 given)
L1.append([60,70]) [10, 20, 30, 40, [60,70]]
print(Lst1)
L2.extend([100]) [80, 90,100]
print(Lst2)
L2.extend(200) TypeError: 'int' object is not
print(Lst2) iterable
L1.extend([60,70]) [10, 20, 30, 40, 50, 60, 70]
print(Lst1)

 Inserting elements of a list


o The list insert() method inserts an element to the list at the specified index.
o This function is used to add elements to list like append() and extend(). However both
append() and extend() insert the element at the end of the list. But insert() allows us to add
new elements anywhere in the list i.e. at position of our choice
o Syntax : <List>.insert(index,element)
Here, index - the index where the element needs to be inserted
element - this is the element to be inserted in the list

Code: Output:
Lst = [ 10, 20, 40]
Lst.insert(2,30)
print(Lst) [10, 20, 30, 40]

Artificial Intelligence 7 Class 10


Unit 3: Advance Python Vision 2 Win

Lst. insert (-2,200)


print(Lst) [10, 20, 30, 200, 40]
Lst. insert (2,[80, 90])
print(Lst) [10, 20, [80, 90], 30, 40]
To insert at Beginning
Lst.insert(0,5) [5, 10, 20, 30, 40]
print(Lst)

To insert at Last
Lst.insert(len(Lst),100) [5, 10, 20, 30, 40, 100]
print(Lst)

REMOVING AN ELEMENT TO A LIST.


 Deletion of List elements Using del():
o To delete items from list we will use del statement. To delete single item give index, and to
delete multiple items use slicing.
o Syntax : del <List>[index]

o Example:

Code: Output:
Lst = [ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ]
del Lst[2]
print(Lst) [10, 20, 40, 50, 60, 70, 80, 90,
100]
del Lst[-1]
print(Lst)
[10, 20, 40, 50, 60, 70, 80, 90]
del Lst[2:6]
print(Lst) [10, 20, 80, 90]
del Lst[15]
IndexError: list assignment
print(Lst)
index out of range

Lst = [ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ] [10, 20, 40, 50, 60]
del Lst[4:]
print(Lst)
Lst = [ 10, 20, 80, 90] Deletes all elements…
del Lst NameError: name 'l' is not
print(Lst) defined
Lst = [ 10, 20, 80, 90]
del Lst[:] [] // Empty List
print(Lst)
Lst = [ 1,2,3,4,5,6,7,8,9,10 ]
del Lst[0:10:2] [2, 4, 6, 8, 10]

Artificial Intelligence 8 Class 10


Unit 3: Advance Python Vision 2 Win

print(Lst)
Lst = [ 1,2,3,4,5,6,7,8,9,10 ]
del Lst[::3] [2, 3, 5, 6, 8, 9]
print(Lst)
o Note: If we use del items then it will delete all the elements and the list too i.e. now no list
with the name items will exist in python.

 Remove an item Using pop():


o Removes the item at the specified position and get the value of that item with pop().
o The index at the beginning is 0 (zero-based indexing).
o Syntax : <List_Object>.pop(index) // it deletes the item at the specified position
<List_Object>.pop() // if index is not passed last item will be deleted
o Example: Lst=[10, 20, 30, 40, 50, 60]
Code: Output:
Lst.pop(2) 30
print(Lst) [10, 20, 40, 50, 60]
Lst.pop(-1) 60
print(Lst) [10, 20, 40, 50]
Lst.pop() 60
print(Lst) [10, 20, 40, 50]
Lst.pop(10) IndexError: pop index out of
print(Lst) range.
Code: Output:
Lst=[]
print(Lst) []
Lst.pop() IndexError: pop from empty
list

 Remove an item Using remove():


o remove() function is used to remove element whose position is given, but what if you know
the value to be removed, but you don’t know its index or position in the list then remove()
function used.
o It remove the first occurrence of given item from the list and return error if there is no such
item in the list. It will not return any value.
o Syntax : <List_Object>.remove(index)

o Example: Lst=[10, 20, 30, 40, 30, 50, 30]


Code: Output:
Lst.remove(40) 40
print(Lst) [10, 20, 30, 30, 50, 30]

Artificial Intelligence 9 Class 10


Unit 3: Advance Python Vision 2 Win

Lst.remove(30) 30
print(Lst) [10, 20, 30, 50, 30]
It remove the first occurrence of given item from the
list
Lst.remove(100) ValueError: list.remove(x).x not in list
print(Lst)
Lst.remove() TypeError: remove() takes exactly one argument (0
print(Lst) given)

 Remove all items: clear()


o This function removes all the items from the list and the list becomes empty list.
o Syntax : <List_Object>.clear()
o Example: Lst=[10, 20, 30, 40, 30, 50, 30]
Code: Output:
Lst.clear() []
print(Lst)

o Note: unlike ‘del listname’ statement, clear() will removes only the elements and not the list.
After clear() the list object still exists as an empty list.

 copy()
o The copy() method returns a shallow copy of the list.A list can be copied using the = operator.
o Syntax : <New_List> = <Old_List>.copy()

Code: Output:
L1=[10, 20, 30, 40, 50]
L2 = L1.copy()
print(L1) [10, 20, 30, 40, 50]
print(L2) [10, 20, 30, 40, 50]

 count()
o This function returns the count of the item that you passed as an argument. If the given item is
not in the list, it returns zero.
o OR The count() method returns the number of times element appears in the list.
o Syntax : < List_object >.count(element)
Here, element - the element to be counted.

o Example: Lst=[10, 20, 30, 10, 50, 10, 60, 10, 10]

Code: Output:
print(Lst.count(10)) 5
print(Lst.count(20)) 1

Artificial Intelligence 10 Class 10


Unit 3: Advance Python Vision 2 Win

print(Lst.count(100)) 0

 reverse()
o This function reverses the items in the list. This is done in place, i.e. It will not create a new list.
o Syntax : <List_object>.reverse()
Code: Output:
Lst=[10, 20, 30, 40, 50]
print(Lst) [10, 20, 30, 40, 50]
Lst.reverse() [50, 40, 30, 20, 10]
print(Lst)
Lst= [‘c,’d’,’e’,’b’,’a’] Output:
print(Lst) [‘c,’d’,’e’,’b’,’a’]
Lst.reverse()
print(Lst) [‘a’, ’b’, ’e’, ’d’, ’c’]

L1=[1, 2, 3] Output:
L2=L1.reverse()
print(L1) [3, 2, 1]
print(L2) None

 sort()
o This function sorts the items of the list, by default increasing order. This is done «in place» i.e.
It does not create new list.
o Syntax : <List_object>.sort() // By default increasing order (Ascending order)
<List_object>.sort(reverse=True) //By default decreasing order (Descending order)
Code: Output:
Lst= [10, 50, 40, 30, 20]
print(Lst) [10, 50, 40, 30, 20]
Lst.sort()
print(Lst) [10, 20, 30, 40, 50]
Lst= [10, 50, 40, 30, 20] Output:
print(Lst) [10, 50, 40, 30, 20]
Lst.sort(reverse=True)
print(Lst) [50, 40, 30, 20, 10]
Lst= [‘c,’d’,’e’,’b’,’a’] Output:
print(Lst) [‘c,’d’,’e’,’b’,’a’]
Lst.sort(reverse=True)
print(Lst) [‘a’, ’b’, ’c’, ’d’, ’e’]
L1=[3, 1, 4, 2] Output:
L2=L1.sort()
print(L1) [1, 2, 3, 4]
print(L2) None

Artificial Intelligence 11 Class 10


Unit 3: Advance Python Vision 2 Win

o Note: If a list contains a complex number, sort will not work.

 min()
o Return item with minmum value in the list.
o Syntax : min(List_Seq)

o Example: Lst=[10, 20, 30, 40, 30, 50, 30]


Code: Output:
Lst=[10, 20, 30, 40, 30, 50, 30] 10
print(min(Lst))

 max()
o Return item with maximum value in the list.
o Syntax : max(List_Seq)

o Example: Lst=[10, 20, 30, 40, 30, 50, 30]

Code: Output:
Lst=[10, 20, 30, 40, 30, 50, 30] 50
print(max(Lst))

 list()
o Converts a tuple, string, set, dictionary into list.
o Syntax : list(Seq)

o Example:
Code: Output:
Lst=(10, 20, 30, 10, 50, 10, 60, 10) [10, 20, 30, 10, 50, 10, 60,10]
l1=list(Lst)
print(l1)
Str=”INDIA” ['I', 'N', 'D', 'I', 'A']
s=list(Str)
print(s)

Tuples
 Introduction :
o TUPLE is a collection of items and each item has its own index value.
o Tuple is a standard data type of Python. It is a sequence which can store values of any kind.

Artificial Intelligence 12 Class 10


Unit 3: Advance Python Vision 2 Win

o Tuple is represented by round brackets / parentheses “ ( ) “


o Tuple is an immutable data type which means we cannot change any value of tuple.
o In Python Tuple is a sequence of items and each item can be individually access using index.
From beginning the first item in Tuple is at index 0 and last will be at len-1. From backward
direction last item will be at index -1 and first item will be at –len.

Forward indexing
0 1 2 3 4 5 6 7 8 9 Positive Index

70 10
10 20 30 40 50 60 80 90 Values
0
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Negative Index

Backward indexing
 Creating & Initializing Tuple:
 Creating a tuple
 Tuples are enclosed in parentheses () and each item is separated by a comma.
 Syntax: TupleName = ( )
o Creating tuple from existing sequences (i.e. Using tuple() function…
 Syntax: TupleName = tuple(sequence)
Code: Output:
>>>Mytuple = tuple(‘Hello’) (‘H’,’e’,’l’,’l’,’o’)
>>>Mytuple
Code: Output:
>>>Mytuple = [‘H’,’e’,’l’,’l’,’o’] (‘H’,’e’,’l’,’l’,’o’)
>>>Mytuple1 = tuple(Mytuple)
>>>Mytuple1

o Creating tuple from existing sequences (i.e. Using input() function…)


 We can also create tuple of single characters or single digits through input() function.
 Syntax: TupleName = tuple(input(“Statements”))
Code: Output:
>>>Mytuple = tuple(input(“Enter Tuple Elements :”)) (‘1’,’2’,’3’,’4’,’5’)
Enter Tuple Elements : 12345
>>>Mytuple
Note: when we input values as numbers to a tuple even then numbers automatically converted
to Tuple.

 Initializing a tuple
 Passing value in tuple while declaring tuple is initializing of a tuple.
 Syntax: TupleName = ( value1, value2,…..)

o TUPLE can also be created Using Initialization methods…


Code: Output:

Artificial Intelligence 13 Class 10


Unit 3: Advance Python Vision 2 Win

>>>Mytuple = (‘H’,’e’,’l’,’l’,’o’) (‘H’,’e’,’l’,’l’,’o’)


>>>Mytuple
o Ex:
 Tuple=()
 Tuple=(1,2)
 Tuple=(1,2,13.34,16.24)
 Tuple=(1,2,(1,2,3,4))
 Tuple=(1,2,[1,2,3,4])

 Accessing Tuple Elements:


o Tuple is a sequence like a string. Tuple also has index of each of its element. Values can be
accessed like string.
o In Python, individual item of a Tuple can be accessed by using the method of Indexing.
Index is positive address references to access item from the forward of the Tuple & allows
negative address references to access item from the back of the Tuple,
o While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.
o Ex: n=( 10,20,30,40,50,60,70,80,90,100)

0 1 2 3 4 5 6 7 8 9
10 20 30 40 50 60 70 80 90 100
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Code: Output:
>>> n=( 10,20,30,40,50,60,70,80,90,100)
>>>n[1] 20
>>>n[5] 60
>>>n[-3] 80
>>>n[15] Index Error
>>>n[3:8] (40,50,60,70)

 Traversal /Iterating of a tuple


o Traversal of a tuple means to access and process each and every element of that tuple.
o Process of accessing each and every element of a tuple for the purpose of display or for some
other purpose is called Traversal.
o It means accessing the individual element of tuple i.e. from first element to last element.
o Every element in tuple is at different index position i.e. from 0 to size-1.
o Traversal of a tuple is very simple with for loop.
Code: Output:
tpl = (‘I’,’N’,’D’,’I’,’A’) I-N-D-I-A-
for i in tpl :
print(i,end=’-‘)

Artificial Intelligence 14 Class 10


Unit 3: Advance Python Vision 2 Win

Code: I
tpl = (‘I’,’N’,’D’,’I’,’A’) N
for i in tpl: D
print(i) I
A
Code: Output:
tpl = (‘I’,’N’,’D’,’I’,’A’) Index 0 and the element at index -5 is I
l=len(lst) Index 1 and the element at index -4 is
for i in range(0,l): N
print(“Index “,i,” and the element at index“, Index 2 and the element at index -3 is
(i-l),”is”, tpl (i)) D
Index 3 and the element at index -2 is I
Index 4 and the element at index -1 is
A

 Tuple operators
o There are many operations that can be performed with Tuple which makes it one of the most
used data types in Python.
o Two basic operators + and * are allowed
 + is used for concatenation (joining)
 * Is used for replication (repetition)

o Tuple Concatenation Operator (Joining) (+):


 Joining of two or more Tuple into a single one is called Concatenation.

 Syntax:
<Tuple1> + <Tuple2>

 Example:
(10,20,30) + (40,50)  (10,20,30,40,50)
(‘I’) + (“Love”) + (“India”)  (‘I’,“Love”,“India”)

Code: Output:
>>> T1=( 10,20,30,40,50)
>>>T2=(60,70,80,90,100) (10,20,30,40,50,60,70,80,90,100)
>>>T3 = T1 + T2
>>>T3
 Note: you can only add tuple with another tuple not with int, float, complex, or string
type.
(10,20,30) + 5  Invalid

o Tuple Replication Operator (Repetition) (*):


 The * operator can be used to repeat the Tuple for a given number of times.
 * needs two types of operands, i.e. a Tuple and a number.
 Syntax:
<Tuple> * <Number>

Artificial Intelligence 15 Class 10


Unit 3: Advance Python Vision 2 Win

 Example:
(10,20,30) * 3  (10,20,30,10,20,30,10,20,30)
(‘I’,“Love”,“India”) *2  (‘I’,“Love”,“India”,‘I’,“Love”,“India”)
 Note: you cannot multiply tuple and tuple using *. Only number*tuple or tuple*number is
allowed.
(10,20,30) * (40,50,60)  Invalid

 Membership operators (in & not in)


o in operator: Evaluates to true if it finds a variable in the specified sequence and false
otherwise. OR Returns true if a element exist in the given tuple, else false.
o not in operator: Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise. OR Returns true if a element does not exist in the given tuple, else false.
 Syntax:
<element> in <tuple>
<element> not in <tuple>
 Example:
20 in (10,20,30,40)  True
50 in (10,20,30,40)  False
10 not in (10,20,30,40)  False
“Ind” in (“Ind”,US)  True
“e” in (‘K’,’e’,’n’,’s’,’r’,’i’)  True
“z” in (‘K’,’e’,’n’,’s’,’r’,’i’)  False

 Tuple Slicing
o As we know slice means “part of”, so slicing is a process of extracting part of tuple.
o OR Slicing is a part of a tuple containing some continuous character from the tuple.
o The tuple are sliced using a range of indices (Tuple characters have their unique index
position from 0 to length-1 and -1 to –length(backward)).

o Syntax: seq = tuple ( start : stop ) OR seq = tuple ( start : stop : step )
Where start & stop are integer, and start is staring index value, stop is ending index
value & step is stepping index.

o Example1: Tpl1 = ( 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 )
Tpl1[: ] / Tpl1[ : :] / Tpl1  ( 10, 20, 30, 40, 50, 60, 70, 80, 90 )
Tpl1[ 2 : 5 ]  ( 30, 40, 50 )
Tpl1[ 3 : -3 ]  ( 40, 50, 60 )
Tpl1[ 0 : 10 : 2 ]  ( 10, 30, 50, 70, 90 )
Tpl1[ : : 3 ]  ( 10, 40, 70 )
Tpl1[ : : -1 ]  ( 90, 80, 70, 60, 50, 40, 30, 20, 10 )
Tpl1[ : : -2 ]  ( 90, 70, 50, 30, 10 )
Tpl1[ -4 : -1 ]  ( 60, 70, 80 )
Tpl1[ : : 3 ]  ( 10, 40, 70 )

Artificial Intelligence 16 Class 10


Unit 3: Advance Python Vision 2 Win

Tpl1 [ 4 ]  ( 50 )
Tpl1[ 15 ]  IndexError: tuple index out of range

o Example2: Tpl1 = ('I','N','D','I','A')


Tpl1( 0 : 3 )  ('I', 'N', 'D')
Tpl 1( 3 : )  ('I', 'A')
Tpl 1(:)  ('I', 'N', 'D', 'I', 'A')

 Unpacking tuples
o Creating a tuple from a set of values is called packing and its reverse i.e. creating individual
values from tuple‟s elements is called unpacking.
o Syntax: var1, var2, var3, … = tuple_Object

o Example:
Tpl1 = (100,200,300,400,500)
a,b,c,d,e=Tpl1
print(a)  100
print(b)  200
print(c)  300
print(d)  400
print(e)  500

 Use of slicing for tuple Modification


Code: Output:
T =("One","Two","Three")
print(T) ('One', 'Two', 'Three')

T[0:2]=(0,1) TypeError: 'tuple' object does


print(T) not support item assignment.
T[2:0]= "604" TypeError: 'tuple' object does
print(T) not support item assignment
Bcoz Tuple Immutable

 TUPLE FUNCTIONS AND METHODS


o Python offers many built-in functions for Tuple manipulation.

o Syntax: <Tuple_Object> . <functionName> ()

 index(substring) :
o This function returns index position of substring.
o If substring not it returns error ‘substring not found’

Artificial Intelligence 17 Class 10


Unit 3: Advance Python Vision 2 Win

o OR This function is used to get the index of first matched item from the tuple. It returns
index value of item to search
o Syntax : <Tuple_Object>.index(substring) :
o Example:

Code: Output:
Tpl=(10,20,30,40,50,60,70,80,90,100) 4
print(Tpl. index (50))
Code: Output:
Tpl=(10,20,30,40,50,60,70,80,90,100) ValueError: tuple.index(x): x
print(Tpl. index (200)) not in tuple.

o Note: if we pass any element which is not in the tuple then index function will return an
error.

 len(string) :
o This function returns the number of characters in any tuple including spaces.
o Syntax : len( <Tuple_Object> )
o Example:

Code: Output:
Tpl=(10,20,30,40,50,60,70,80,90,100) 10
print(len(Tpl))
Code: Output:
Tpl=(‘I’,’N’,’D’,’I’,’A’) 5
print(len(Tpl))

 Deletion of Tuple elements Using del():


o As we know that tuple is of immutable type, it is not possible to delete an individual element
of a tuple. With del() function, it is possible to delete a complete tuple.
o Direct deletion of tuple element is not possible but shifting of required content after discard
of unwanted content to another tuple.
o The del statement of python is used to delete elements and objects but as you know that
tuples are immutable, which also means that individual elements of tuples cannot be deleted.
o Syntax : del <Tuple>

o Example:

Code: Output:
Tpl = ( 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 )
del Tpl(2) TypeError: 'tuple' object doesn't
print(Tpl) support item deletion.
Error shown because deletion of a
single element is also possible
Tpl = ( 10, 20, 80, 90) Deletes all elements…
del Tpl NameError: name 'Tpl' is not

Artificial Intelligence 18 Class 10


Unit 3: Advance Python Vision 2 Win

print(Tpl) defined
Complete tuple has been deleted. Now
error shown on printing of tuple.

 count()
o This function returns the count of the item that you passed as an argument. If the given item is
not in the tuple, it returns zero. OR The count() method returns the number of times element
appears in the tuple.
o Syntax : < Tuple_object >.count(element)
Here, element - the element to be counted.

o Example: Tpl=(10, 20, 30, 10, 50, 10, 60, 10, 10)

Code: Output:
print(Tpl.count(10)) 5
print(Tpl.count(20)) 1
print(Tpl.count(100)) 0

 sorted()
o This function sorts the items of the tuple, by default increasing order. This is done «in place»
i.e. It does not create new tuple.
o Syntax : <Tuple1>.sorted(Tuple2) // By default increasing order (Ascending order)

Code: Output:
T1= (10, 50, 40, 30, 20)
print(T1) (10, 50, 40, 30, 20)
T2.sorted(T1)
print(T2) (10, 20, 30, 40, 50)

o Note: If a tuple contains a complex number, sort will not work.

 min()
o Returns item from the tuple with min value.can be done via list
o Syntax : min(Tuple_Seq)

o Example:
Code: Output:
T=(10, 20, 30, 40, 30, 50, 30) 10
print(min(T))

 max()
o Returns item from the tuple with max value.can be done via list.
o Syntax : max(Tuple_Seq)

Artificial Intelligence 19 Class 10


Unit 3: Advance Python Vision 2 Win

o Example:
Code: Output:
T=(10, 20, 30, 40, 30, 50, 30) 50
print(max(T))

 tuple()
o Converts a list into tuple.
o Syntax : tuple(Seq)

o Example:
Code: Output:
T=[10, 20, 30, 10, 50, 10, 60, 10] (10, 20, 30, 10, 50, 10, 60,10)
T1=tuple(T)
print(T1)
Str=”INDIA” ('I', 'N', 'D', 'I', 'A')
s=tuple(Str)
print(s)
 sum()
o sum of tuple elements can be done via list
o Syntax : sum(list(Seq))

o Example:
Code: Output:
T=(10, 20, 30]) Sum= 60
T1= sum(list(T)
print(“Sum =”,T1)

Dictionaries
 Introduction:
o Python provides us various options to store multiple values under one variable name.
o Dictionaries are also a collection like a string, list and tuple.
o It is a very versatile data type.
o There is a key in it with a value.(KEY:VALUE)
o Dictionaries are mutable data types and it is an unordered collection in the form of
KEY:VALUE
o In List, index of a value is important whereas in dictionary, key of a value is important.
o It is an unordered collection of items where each item consists of a key and a value.
o It is mutable (can modify its contents) but Key must be unique and immutable

Artificial Intelligence 20 Class 10


Unit 3: Advance Python Vision 2 Win

 Creating a Dictionary
o It is enclosed in curly braces {} and each item is separated from other item by a comma(,).
Within each item, key and value are separated by a colon (:).
o Passing value in dictionary at declaration is dictionary initialization.get() method is used to
access value of a key.
o Syntax:
<dictionary-name>={ <key1>:<value1>,<key2>:<value2>,<key3>:<value3>. . . }

o Example: emp = {"empno":1,"name":"Shahrukh","fee":1500000}


Here, Keys are: “empno”, “name” and “fee”
Values are: 1, “Shahrukh”, 1500000

o Creating
Dict1 = {} # empty dictionary
DaysInMonth={"Jan":31,"Feb":28,"Mar":31,"Apr":31,"May":31,"Jun":30,"Jul":31,
"Aug":31,"Sep":30,"Oct":31,"Nov":30,"Dec":31}

 Accessing elements of Dictionary


o To access a value from dictionary, we need to use key similarly as we use an index to access a
value from a list.
o We get the key from the pair of Key: value.
Code: Output:
dict = {'Subject': ‘C.Sc’, 'Class': 11}
print(dict) {'Class': '11', 'Subject': 'C.Sc'}
print ("Subject : ", dict['Subject']) ('Subject : ', C.Sc')
print ("Class : ", dict.get('Class')) ('Class : ', 11)
dict[“DOB”] #Error

o Note: if you try to access “key” which is not in the dictionary, python will raise an error.

 Traversing a Dictionary
o It means accessing & processing each & every element of dictionary.
o Python allows to apply “for” loop to traverse every element of dictionary based on their
“key”. For loop will get every key of dictionary and we can access every element based on
their key.
o Syntax : for <item> in <dictionary>:

Code: (Printing only values) Output:


dict = {'Subject': ‘IP’, 'Class': 11}
print(dict) {'Class': '11', 'Subject': IP}
for i in dict: IP
print(dict[i]) 11

Artificial Intelligence 21 Class 10


Unit 3: Advance Python Vision 2 Win

Code: (Printing both keys : values) Output:


dict = {'Subject': ‘C.Sc’, 'Class': 11}
print(dict) {'Class': '11', 'Subject': 'C.Sc'}
for i in dict: Subject : C.Sc
print(i, “ : “, dict[i]) Class :11

 Accessing keys and values simultaneously


o To access key and value we need to use keys() and values().
o Syntax:
 To access key : <Dict Name>.keys()
 To access value : <Dict Name>.values().
Code: Output:
dict = {'Subject': ‘C.Sc’, 'Class': 11,’Salary’ : 20000}
dict.keys() ['Subject', 'Class',’Salary’]
dict.values() [‘C.Sc’, 11, 20000]

 Updating elements in Dictionary


o We can change the individual element of dictionary.
o Syntax : Dictionaryname[“key”]=value.

Code: Output:
stud = dict(( ( “Name”, “Ravi”), (“Cource”,”XI”) )) {“Name”: “Ravi”, “Cource”:”XI”}
stud
stud[“fees”]=45000 {“Name”: “Ravi” , “Cource”:”XI”,
stud “fees”:45000}
stud[“Subject”]=“C.Sc”
stud {“Name”: “Ravi” , “Cource”:”XI”,
“fees”:45000, “Subject“ : “C.Sc“}

 Deleting elements from Dictionary


o It is used to delete element from dictionary.
o There are two methods.
o Using del:
 It only deletes the value and does not return deleted value.
 Syntax : del <dictionary>[<key>]
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000} {“Ravi” : 45000, “Nagu” ;
print(emp) 50000, “Roki” : 30000}
del emp[“Ravi”] { “Nagu” ; 50000,

Artificial Intelligence 22 Class 10


Unit 3: Advance Python Vision 2 Win

print(emp) #Value did not return after deletion. “Roki” : 30000}

o Using pop():
 It returns the deleted value after deletion.
 Syntax : <dictionary>.pop(<key>)
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000}
emp.pop(“Ravi”) 45000
print(emp) # Value returned after deletion. { “Nagu” ; 50000,
emp.pop(“Ravi”,”Not Found”) “Roki” : 30000}
#If key does not match, given message will be printed. Not Found

o Using clear():
 It is used to remove all elements from the dictionary.
 Syntax : <dictionary>.clear(<key>)
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000} {“Ravi” : 45000, “Nagu” ;
print(emp) 50000, “Roki” : 30000}
emp.clear() {}

 Dictionary Function and Method


o len() :
 It return the length of dictionary i.e. the count of elements (key:value pairs) in dictionary.
 Syntax : len(<dictionary>)
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000} ['india', 'is', 'my', 'country']
len(emp)

o get() :
 This method is used value of given key, if key not found it raises an exception.
 OR It is used to get/read the item with the given key. Similarly dict[key]=value. If key
not present it returns error (Key is not defined).
 Syntax : <dictionary> . get (key , [default] )
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000}
emp.get(“Nagu”) 50000
emp.get(“Janu”,”Not Found”) Not Found

o items() :
 This method returns all the items in the dictionary s a sequence of (key,value) tuple.

Artificial Intelligence 23 Class 10


Unit 3: Advance Python Vision 2 Win

 OR It is used to get/read the item with the given key. Similarly dict[key]=value. If key
not present it returns error (Key is not defined).
 Syntax : <dictionary> . items ()
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000} ('Ravi', 45000)
mylist=emp.items() ('Nagu', 50000)
for k in mylist : ('Roki', 30000)
print (k)

o keys() :
 This method return all the keys in the dictionary as a sequence of keys(not in list form).
 Syntax : <dictionary> . keys()
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000} ['Ravi', 'Nagu', 'Roki']
emp.keys()

o values() :
 This method return all the values in the dictionary as a sequence of keys(a list form).
 Syntax : <dictionary> . values()
Code: Output:
emp={“Ravi” : 45000, “Nagu” : 50000, “Roki” : 30000} [45000, 50000, 30000]
emp.values()

o Update() method :
 This function merges the dictionary into other dictionary.
 This method merges the key:value pair from the new dictionary into original dictionary,
adding or replacing as needed. The items in the new dictionary are added to the old one
and override items already with the same keys.
 Syntax : <dictionary-1> . update(<dictionary-2>)
Code: Output:
emp1={“Name” : “Ravi”, “Salary” : 50000, “Age” : 30}
emp2={“Name” : “Nagu”, “Salary” : 55000, “Dept” : “AO”} {“Name” : “Nagu”,
emp1.update(emp2) “Salary” : 55000,
print(emp1) “age””30, “Dept” : “AO”}
print(emp2)
{“Name” : “Nagu”,
“Salary” : 55000,
“Dept” : “AO”}

o copy() :
 It will create a copy of dictionary OR returns a shallow copy of the dictionary.
 Syntax : <dictionary-2> =(<dictionary-1>).copy()

Artificial Intelligence 24 Class 10


Unit 3: Advance Python Vision 2 Win

Code: Output:
emp1={“Name” : “Ravi”, “Salary” : 50000, “Age” : 30} {“Name” : “Ravi”, “Salary” :
emp2={} 50000, “Age” : 30}
emp2=emp1.copy()
print(emp1) {“Name” : “Ravi”, “Salary” :
print(emp2) 50000, “Age” : 30}

o popitem()
 It will remove the last dictionary item are return key, value.
 Syntax : <key>,<value> . <dictionary>.popitem()
Code: Output:
emp1={“Name” : “Ravi”, “Salary” : 50000, “Age” : 30} “Age” : 30
k, v =emp1.popitem()
print(k,v)

o max() & min()


 max() returns highest value in dictionary, this will work only if all the values in
dictionary is of numeric type.
 min() returns smallest value in dictionary, this will work only if all the values in
dictionary is of numeric type.
 Syntax : max(<dictionary>.values())
min(<dictionary>.values())
Code: Output:
d1={1:1000, 2:2000, 3:3000, 4:5000}
print(max(d1.values())) 5000
print(min(d1.values())) 1000

Artificial Intelligence 25 Class 10

You might also like