Apna Jila * APNA JILA * Apna Jila

8: TUPLE IN PYTHON Back


        

Computer Science Class -XI Code No. 083 2023-24


CLASS-XI
SUBJECT: COMPUTER SCIENCE (083) – PYTHON
INDEX
NO. CHAPTER NAME 
1 INTRODUCTION TO PYTHON 
2 PYTHON FUNDAMENTALS 
3 DATA HANDLING 
4 FLOW OF CONTROL 
5 FUNCTIONS IN PYTHON 
6 STRING IN PYTHON 
7 LIST IN PYTHON 

CHAPTER-7
LIST IN PYTHON
7.1 Introduction:
 List is a collection of elements which is 
ordered and changeable (mutable).
 Allows duplicate values.
 A list contains items separated by commas and 
enclosed within square brackets ([ ]).
 All items belonging to a list can be of 
different data type.
 The values stored in a list can be accessed 
using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list.
Difference between list and string:
List String
Mutable Immutable
Element can be assigned at specified
index
Element/character cannot be
assigned at specified index.
Example:
>>>L=[7,4,8,9]
>>>L[2]=6 #valid
Example:
>>>str= “python”
>>>str[2]= ‘p’ #error
7.2 Creating a list:
To create a list enclose the elements of the 
list within square brackets and separate the
elements by commas.
Syntax:
list-name= [item-1, item-2, …….., item-n]
Example:
mylist = ["apple", "banana", "cherry"] 
# a list with three items
L = [ ] # an empty list
7.2.1 Creating a list using list( ) Constructor:
o It is also possible to use the list( ) 
constructor to make a list.

mylist = list(("apple", "banana", "cherry"))
#note the double round-brackets
print(mylist)
L=list( ) # creating empty list
7.2.2 Nested Lists:
>>> L=[23,'w',78.2, [2,4,7],[8,16]]
>>> L
[23, 'w', 78.2, [2, 4, 7], [8, 16]]
7.2.3 Creating a list by taking input from the user:
>>> List=list(input("enter the elements: "))
enter the elements: hello python
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1=list(input("enter the elements: "))
enter the elements: 678546
>>> L1
['6', '7', '8', '5', '4', '6']
# it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method,
which identifies the
data type and evaluate them automatically.
>>> L1=eval(input("enter the elements: "))
enter the elements: 654786
>>> L1
654786 # it is an integer, not a list
>>> L2=eval(input("enter the elements: "))
ApnaJila ApnaJila 63
enter the elements: [6,7,8,5,4,3] # for list, 
you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements
without square bracket[ ], it will be
considered as a tuple.
>>> L1=eval(input("enter the elements: "))
enter the elements: 7,65,89,6,3,4
>>> L1
(7, 65, 89, 6, 3, 4) #tuple
7.3 Accessing lists:
 The values stored in a list can be accessed using 
the slice operator ([ ] and [:]) with
indexes.
 List-name[start:end] will give you elements 
between indices start to end-1.
 The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
Forward Index
Backward Index
ApnaJila ApnaJila 64
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
7.4 Traversing a LIST:
Traversing means accessing and processing each element.
Method-1:
>>> day=list(input("Enter elements :"))
Enter elements : sunday
>>> for d in day:
print(d)
Output:
s
u
n
d
a
y
Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])
Output:
w
e
d
n
e
s
d
a
y
7.5 List Operators:
 Joining operator +
 Repetition operator *
 Slice operator [ : ]
 Comparison Operator <, <=, >, >=, ==, !=
ApnaJila ApnaJila 65
 Joining Operator: It joins two or more lists.
Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
['a', 56, 7.8, 'b', '&', 6, 67, 'f', 'p']
 Repetition Operator: It replicates a list specified number of times.
Example:
>>> L1*3
['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]
>>> 3*L1
['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]
 Slice Operator:
List-name[start:end] will give you elements between indices start to end-1.
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
[87, 45, 23, 97]
>>> number[4:20]
[23, 97, 56, 27]
>>> number[-1:-6]
[ ]
>>> number[-6:-1]
[87, 45, 23, 97, 56]
ApnaJila ApnaJila 66
>>> number[0:len(number)]
[12, 56, 87, 45, 23, 97, 56, 27]
List-name[start:end:step] will give you elements between 
indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[56, 45, 97]
>>> number[: : -1]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
List modification using slice operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
[12, 56, 'hello', 'python', 23, 97, 56, 27]
>>> number[2:4]=["computer"]
>>> number
[12, 56, 'computer', 23, 97, 56, 27]
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:3]=78 # 78 is a number, not a sequence
TypeError: can only assign an iterable
ApnaJila ApnaJila 67
 Comparison Operators:
o Compares two lists
o Python internally compares individual elements of lists in lexicographical
order.
o It compares the each corresponding element must compare equal and two
sequences must be of the same type.
o For non-equal comparison as soon as it gets a result in terms of True/False,
from corresponding elements’ comparison. If Corresponding elements are
equal, it goes to the next element and so on, until it finds elements that differ.
Example:
>>>L1, L2 = [7, 6, 9], [7, 6, 9]
>>>L3 = [7, [6, 9] ]
For Equal Comparison:
Comparison Result Reason
>>>L1==L2 True Corresponding elements have same value and same
type
>>>L1==L3 False Corresponding values are not same
For Non-equal comparison:
Comparison Result Reason
>>> L1>L2 False All elements are equal
>>> L2>L3 TypeError: '>' not
supported between
instances of 'int' and
'list'
in L2, element at the index 1 is int type
and in L3 element at the index 1 is list
type
>>>[3,4,7,8]<[5,1] True 3<5 is True
>>>[3,4,7,8]<[3,4,9,2] True First two elements are same so move
to next element and 7<9 is True
>>>[3,4,7,8]<[3,4,9,11] True 7<9 is True
>>>[3,4,7,8]<[3,4,7,5] False 8<5 is False
ApnaJila ApnaJila 68
List Methods:
Consider a list:
company=["IBM","HCL","Wipro"]
S.
No.
Function
Name Description Example
1 append( ) To add element to the list
at the end.
Syntax:
list-name.append (element)
>>> company.append("Google")
>>> company
['IBM', 'HCL', 'Wipro', 'Google']
Error:
>>>company.append("infosys","microsoft") # takes exactly one element
TypeError: append() takes exactly one argument (2 given)
2 extend( ) Add a list, to the end of
the current list.
Syntax:
list-name.extend(list)
>>>company=["IBM","HCL","Wipro"]
>>> desktop=["dell","HP"]
>>> company.extend(desktop)
>>> company
['IBM', 'HCL', 'Wipro', 'dell', 'HP']
Error:
>>>company.extend("dell","HP") #takes only a list as argument
TypeError: extend() takes exactly one argument (2 given)
3. len( ) Find the length of the list.
Syntax:
len(list-name)
>>>company=["IBM","HCL","Wipro"]
>>> len(company)
3
>>> L=[3,6,[5,4]]
>>> len(L)
3
4 index( ) Returns the index of the
first element with the
specified value.
Syntax:
list-name.index(element)
>>> company = ["IBM", "HCL", "Wipro",
"HCL","Wipro"]
>>> company.index("Wipro")
2
Error:
>>> company.index("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list
ApnaJila ApnaJila 70
9 pop( ) Removes the element at
the specified position and
returns the deleted
element.
Syntax:
list-name.pop(index)
The index argument is
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.
>>>company=["IBM","HCL", "Wipro"]
>>> company.pop(1)
'HCL'
>>> company
['IBM', 'Wipro']
>>> company.pop( )
'Wipro'
Error:
>>>L=[ ]
>>>L.pop( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list.
Syntax:
list-name.copy( )
>>>company=["IBM","HCL", "Wipro"]
>>> L=company.copy( )
>>> L
['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the
list.
Syntax:
list-name.reverse( )
Takes no argument,
returns no list.
>>>company=["IBM","HCL", "Wipro"]
>>> company.reverse()
>>> company
['Wipro', 'HCL', 'IBM']
12. sort( ) Sorts the list. By default
in ascending order.
Syntax:
list-name.sort( )
>>>company=["IBM","HCL", "Wipro"]
>>>company.sort( )
>>> company
['HCL', 'IBM', 'Wipro']
To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> company.sort(reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
ApnaJila ApnaJila 71
Deleting the elements from the list using del statement:
Syntax:
del list-name[index] # to remove element at specified index
del list-name[start:end] # to remove elements in list slice
Example:
>>> L=[10,20,30,40,50]
>>> del L[2] # delete the element at the index 2
>>> L
[10, 20, 40, 50]
>>> L= [10,20,30,40,50]
>>> del L[1:3] # deletes elements of list from index 1 to 2.
>>> L
[10, 40, 50]
>>> del L # deletes all elements and the list object too.
>>> L
NameError: name 'L' is not defined
ApnaJila ApnaJila 72
Difference between del, remove( ), pop( ), clear( ):
S.
No. del remove( ) pop( ) clear( )
1 Statement Function Function Function
2
Deletes a single element
or a list slice or complete
list.
Removes the first
matching item
from the list.
Removes an
individual item and
returns it.
Removes all the
elements from list.
3
Removes all elements
and deletes list object
too.
Removes all
elements but list
object still exists.
Difference between append( ), extend( ) and insert( ) :
S.
No. append( ) extend( ) insert( )
1 Adds single element in the end
of the list.
Add a list in the end of
the another list
Adds an element at the
specified position.
(Anywhere in the list)
2 Takes one element as argument Takes one list as
argument
Takes two arguments,
position and element.
3 The length of the list will
increase by 1.
The length of the list
will increase by the
length of inserted list.
The length of the list
will increase by 1.
ACCESSING ELEMENTS OF NESTED LISTS:
Example:
>>> L=["Python", "is", "a", ["modern", "programming"], 
"language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
ApnaJila ApnaJila 73
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
Programs related to lists in python:
Program-1 Write a program to find the minimum and maximum number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
min=L[0]
max=L[0]
for i in range(n):
if min>L[i]:
min=L[i]
if maxsecond:
max=L[i]
seond=max
print("The second largest number in the list is : ", second)
Program-3: Program to search an element in a list. (Linear Search).
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
ApnaJila 


Apna Jila