0% found this document useful (0 votes)
25 views28 pages

CH. 11 AND 12 LIST AND TUPLE MANIPULATION

Uploaded by

Francis King
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)
25 views28 pages

CH. 11 AND 12 LIST AND TUPLE MANIPULATION

Uploaded by

Francis King
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/ 28

CH.

11 LIST MANIPULATION
What is a list in Python?
Ans. A list in Python is a compound data type because it can store
any data type in it.
ListVariable = [List of Values]
L1 = [10,25,3,99,105]
L2 = *“Ram”, “Raheem”, “Deepa”, “Ashok”+
L3 = *1, “Ram”, 2, “Raheem”, 3, “Deepa”+
L4 = *1, “Ram”, 85.25, 2, “Raheem”, 75.5+
L5 = *25, 36, 60.251, 33, 0.25, “Python”+
What is an empty list?
Ans. A list without any element is called empty list.
L=[]
An empty list can also be created as follows:
L = list( )
What is a nested list?
Ans. A list within a list is called as nested list.
>>> L = [1, 2, 3, [10, 20, 30], 4, 5]
>>> L
[1, 2, 3, [10, 20, 30], 4, 5]
>>> L[0]
1
>>> L[0:3] >>> L[3][0]
[1, 2, 3] 10
>>> L[0:5] >>> L[3][0:3]
[1, 2, 3, [10, 20, 30], 4] [10, 20, 30]
>>> L[7]
IndexError: list index out of range
Creating a list using keyboard with list( ) function:
L = list(input("Enter List Element: "))
print("The List is: ",L)
Enter List Element: PYTHON
The List is: ['P', 'Y', 'T', 'H', 'O', 'N']
Enter List Element: 15,75
The List is: ['1', '5', ',', '7', '5']
The list( ) function always creates a string type of list even though if
we enter digits. To enter a list of integers, float, string or compound
data types the following method is used:
L = eval(input("Enter list: "))
print("The list is: ",L)
Enter list: [25,5.5,"Python",100]
The list is: [25, 5.5, 'Python', 100]
The eval( ) Function: This function can be used to evaluate and
return the result of an expression given as a string. E.g.
Result=eval('5*7')
print(Result) # Output will be 35

>>> Expression = eval(input("Enter an Expression: "))


Enter an Expression: 3+5*5-2
>>> print(Expression)
26
Accessing List:
List = eval(input("Enter List Elements: "))
length=len(List)
for L in range(length):
print("At indexes ",L," and ",(L-length),
"Element is: ",List[L])

Enter List Elements: [2.5,10,25,30,45.25,125]


At indexes 0 and -6 Element is: 2.5
At indexes 1 and -5 Element is: 10
At indexes 2 and -4 Element is: 25
At indexes 3 and -3 Element is: 30
At indexes 4 and -2 Element is: 45.25
At indexes 5 and -1 Element is: 125
Comparing List: >>> L1==L5
True
>>> L1=[1,2,3] >>> L1==L3
>>> L2=[4,5] False
>>> L3=[6,7,8] >>> L1==L2
>>> L4=[9,10,11,12] False
>>> L5=[1,2,3] >>> L1<L2
>>> L6=[25,30] True
>>> L7=[6,7,100] >>> L1<L3
True
>>> L4<L6
True
>>> L3<L7
True
>>> L2>L1
True
Creating a Copy of List:

# a = [10, 11, [20, 21], 12] # a = [10, 11, [20, 21], 12]
#b=a # b = list(a)
# print(a) # print(a)
# print(b) # print(b)
# a[0] = 3 * 10 # a[0] = 3 * 10
# a[2][0] = 3 * 10 # a[2][0] = 3 * 10
# print(a) # print(a)
# print(b) # print(b)
# b[0] = 5 * 5 # b[0] = 5 * 5
# b[2][0] = 5 * 5 # b[2][0] = 5 * 5
# print(a) # print(a)
# print(b) # print(b)
Creating a Copy of List: True Copy and Partial True Copy

a = [10, 11, [20, 21], 12]


b = list(a) # b = a.copy()
print("Modifying element which is not nested:")
b[3] += 4
print(a)
print(b)
print("Now modifying nested element:")
b[2][1] += 4
print(a)
print(b)
Joining Lists: Two or more lists can be joined using concatenation operator
+. A List can only be concatenated with other list; no other data types.
>>> L1=[1,2,3] >>> L+[100]
>>> L2=[4,5] [1, 2, 3, 100]
>>> L3=*‘PHY’, ‘CHEM’, ‘BIO’+ >>> L
>>> L4=L1+L2+L3 [1, 2, 3]
>>> L4
[1, 2, 3, 4, 5, ‘PHY’, ‘CHEM’, ‘BIO’]
>>> L1+75
TypeError: can only concatenate list (not "int") to list
>>> L1+"Python“
TypeError: can only concatenate list (not "str") to list
L1 = [1, 2, 3]
L2 = *“Anil”, “Riya”+
L3 = L1 + “Dinesh” #TypeError: can only concatenate list (not "str") to list
L4 = L2 + “Ziya” #TypeError: can only concatenate list (not "str") to list
Replicating Lists: Like strings we can replicate list using *
operator to a specified number of times.
>>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Slicing the Lists: We can create another list from existing list or
we can create list slices as follows: >>> L=L1[0:6:2]
ListSlice = List[start : stop] >>> L
ListSlice = List[start : stop : step] [10, 30, 50]
>>> L1=[10, 20, 30, 40, 50, 60] L=L1[0: :2]
>>> L=L1[0 : 3] >>> L
>>> L [10, 30, 50]
[10, 20, 30] >>> L=L1[: : -1]
>>> L
[60, 50, 40, 30, 20, 10
List Updating:
L1 = [1, 2, 3, 4, 5]
L1[0] = 10 => [10, 2, 3, 4, 5]
L1[0] = [10] => [[10], 2, 3, 4, 5]
L1[0] = 10, 20 => [(10, 20), 2, 3, 4, 5]
L1[0:2] = 10 => TypeError: can only assign an iterable
L1[0:2] = [10, 20] => [10, 20, 3, 4, 5]
L1[0:2] = [10 ] => [10, 3, 4, 5]
L1[0:2] = [10, 20, 30] => [10, 20, 30, 3, 4, 5]
L1[0:2] = (10, 20, 30) => [10, 20, 30, 3, 4, 5]
L1[0:2] = {11: 20, 12: 20} => [11, 12, 3, 4, 5]
L1[0] = "ABC" => ['ABC', 2, 3, 4, 5]
L1[0:2] = "ABC" => ['A', 'B', 'C', 3, 4, 5]
L1[0:2] = "A" => ['A', 3, 4, 5]
L1[10] = 25 => IndexError: list assignment index out of range
L1[10:15] = 25 => TypeError: can only assign an iterable
L1[10:15] = [25] => [1, 2, 3, 4, 5, 25]
L1[10:15] = "ABC" => [1, 2, 3, 4, 5, 'A', 'B', 'C']
del Statement: This statement can be used to remove an
individual item, or to remove all items identified by a slice or to
delete the list from the computer memory.
del List[index]
del List[start : stop] >>> L=[10,20,30]
del List >>> del L[5]
>>> L=[10,20,30,40,50] IndexError: list assignment index out of range
>>> del L[3] >>> del L[1:3]
>>> L >>> L Note: Element deleted by
[10, 20, 30, 50] [10] del can not be assigned to
>>> del L[1:3] >>> L=[50,60,70,80] any variable because this
>>> L >>> del L[5:10] does not return any value.
[10, 50] >>> L
>>> del L [50, 60, 70, 80]
>>> L
NameError: name 'L' is not defined
index( ) Function: This function returns the index of first
matched element from the list.
ListName.index(element)
>>> L=[10,20,30,40,50,30,60]
>>> L.index(40)
3 Index--- 0 1 2 3 4 5 6
>>> L.index(30) Values--- 10 20 30 40 50 30 60
2
>>> L.index(35)
ValueError: 35 is not in list
append( ) Function: This function adds an element at the end of
the list. This function returns None by default..
Syntax:
ListName.append(element)
>>> L=[10,20,30,40,50]
>>> L.append(60)
>>> L
[10, 20, 30, 40, 50, 60]
>>> L1=L.append(70)
>>> print(L1) # L1 is empty because append function
None returns None but L is appended.
>>> L
[10, 20, 30, 40, 50, 60, 70]
extend( ) Function: This function is used to add multiple
elements to a list. This function takes a list as an argument and
appends all of the elements of the argument list to the list object
on which extend( ) is applied. It returns None.
Syntax:
ListName.extend (List)
>>> L1=[10,20,30]
>>> L2=[40,50,60]
>>> L1.extend(L2)
>>> L1
[10, 20, 30, 40, 50, 60]
>>> L3=[70,80,90]
>>> L=L1.extend(L3) # L is empty because extend function
>>> L does not return any value but L1 is
>>> L1 extended.
[10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> L2.extend([70,80])
>>> L2
[40, 50, 60, 70, 80]
insert( ) Function: This function is used to insert an element in
the list at desired index. This function takes two arguments and
returns no value that is None.
Syntax:
ListName.insert (index, element)
Index--- 0 1 2 3 4 0 1 2 3 4 5
Values--- 10 20 30 40 50 10 60 20 30 40 50

>>> L=[10, 20, 30, 40, 50] >>> L.insert(10,80)


>>> L.insert(1,60) >>> L
>>> L [10, 60, 20, 30, 40, 50, 70, 80]
[10, 60, 20, 30, 40, 50] >>> L.insert(-10,90)
>>> L.insert(len(L),70) >>> L
>>> L [90, 10, 60, 20, 30, 40, 50, 70, 80]
[10, 60, 20, 30, 40, 50, 70]
pop( ) Function:
 This function is used to remove an element from the list at
desired index.
 This function takes index as an arguments and returns the value
which is being deleted.
 If no index is passed in the argument then this function
removes the last element from the list.
Syntax: Index--- 0 1 2
ListName.pop (index) >>> L.pop() Values--- 10 20 30
>>> L = [10, 20, 30] 30
>>> L 0 1
>>> L.pop(1)
[10] 10 30
20
>>> L >>> A = L.pop()
0
[10, 30] >>> A
10 10
remove( ) Function:
 This function is used to remove the first occurrence of given
element from the list.
 This function takes a value as an arguments and does not return
anything.
Syntax:
ListName.remove (element)
>>> L=[10,20,30,10,40,10,50] >>> L.remove(55)
>>> L.remove(10) ValueError: list.remove(x): x not
>>> L in list
[20, 30, 10, 40, 10, 50] L.remove()
>>> L.remove(10) TypeError: remove() takes
>>> L exactly one argument (0 given)
[20, 30, 40, 10, 50]
>>> L1 = L.remove(40) # ???
clear( ) Function:
 This function is used to remove all the elements from the list.
 This function does not return anything.
Syntax:
ListName.clear () >>> max(L)
50
>>> L=[20, 30, 40, 10, 50] >>> min(L)
>>> L.clear() 10
>>> L
[]
count( ) Function:
 This function returns the count of the element that you passed
as an argument.
>>> L=[10,15,10,20,30,10]
Syntax:
>>> L.count(10)
ListName.count (element)
3
reverse( ) Function:
 This function reverses the elements of the list and stores in the
same list variable. This function does not return anything.
Syntax: sort( ) Function:
ListName.reverse ()  This function sorts the elements of the
>>> L=[10,5,30] list and stores in the same list variable.
>>> L.reverse() This function does not return anything.
>>> L Syntax:
[ 30,5,10] ListName.count (element)
>>> L=[10,5,25,20]
>>> L.sort()
>>> L
[25,20,10,5]
>>>print(sorted(L)
sorted() does not modify the original list but it returns the sorted list.
Creating a List from a Tuple:
>>> Tuple=(10,20,30)
>>> L=list(Tuple)
>>> L
[10, 20, 30]

Creating a List from a Dictionary:


>>> Dict={1:"Kartik",2:"Deepak",3:"Puja"}
>>> L1=list(Dict)
>>> L1
[1, 2, 3]
CH. 12 TUPLES
Tuple:
 Tuple is same as list i.e. compound data type but immutable.
 The values of a tuple are enclosed in parenthesis.

Example of Tuples:
T1 = ( ) # Empty Tuple
T2 = (1, 2, 3) # Tuple with integers
T3 = (15.25, 36. 45, 105. 105) # Tuple with float numbers
T4 = (15, 35, 45.002, 187, -125.2501) # Tuple with integers and floats
T5 = (“Jai”, “Riya”, “Khushi”) # Tuple with strings
T6 = ([1, 2, 3], [10, 20, 30], [100, 200, 300]) # Tuple with lists
T7 = (1, “A”, “Amit”, 45.5) # Tuple with mixed data types
T8 = ((1, 3, 5), (2, 4, 6), (1, 2, 3, 4, 5, 6)) # Nested tuple
Ways of creating Tuples:
Using Direct Assignment:
T = (1, 2, 3)
Using tuple( ) function:
T = tuple(iterable) # iterable means list, string, dictionary, set, tuple
e.g. T = tuple([1, 2, 3])
a = tuple(eval(input(“Enter elements of tuple:")))
print(a)

Creating a tuple with single element:


T = (9)
Note: Now the above statement will not create a tuple, it will be an integer
data type. To create tuple with single element the following ways are used.
T = (9,) # Just put one comma (,) after the element
T = 9, # This is also valid
Tuple Joining: A tuple can be joined with another tuple only. No other data
types are allowed to join with any tuple.
T1 = (1, 2, 3)
T2 = (10, 20, 30)
T3 = T1 + T2
print(T3) # T3 will have (1, 2, 3, 10, 20, 30)
T1 = (1, 2, 3)
Num = 1
T3 = T1 + Num
TypeError: can only concatenate tuple (not "int") to tuple
T1 = (1, 2, 3)
L = [10, 20, 30]
T3 = T1 + L
TypeError: can only concatenate tuple (not "list") to tuple
T1 = (1, 2, 3)
String = "Python"
T3 = T1 + String
TypeError: can only concatenate tuple (not "str") to tuple
Tuple Replication:
T1 = (1, 2, 3)
T2 = T1 * 2
print(T2) # T2 will have (1, 2, 3, 1, 2, 3)

How tuple is different from list:


List element can be changed in place but tuple element cannot be changed in
place. E.g.
Marks = [15, 25, 30, 35]
Marks[1] = 27 # Assigning another value is allowed.

Marks = (15, 25, 30, 35)


Marks[1] = 27 # Assigning another value is not allowed.
TypeError: 'tuple' object does not support item assignment
Indirect Modification of Tuples using Tuple Unpacking:
>>> T = (1, 2, 3)
Step 1: First unpack the tuple.
>>> a, b, c = T # Un-packing
Step 2: Change the value.
>>> a = 10
Step 3: Re-pack the tuple with the changed value
>>> T = (a, b, c)
>>> T
(10, 2, 3) # Now the tuple is changed
Indirect Modification of Tuples using constructor functions i.e.
list( ) and tuple( ):
>>> T = (10, 20, 30)
Step 1: Convert the tuple to list using list ( ) function:
>>> L = list(T)
>>> L
[10, 20, 30]
Step 2: Make changes in the desired element in the list
>>> L[0] = 100
>>> L
[100, 20, 30]
Stpe 3: Create a tuple from the modified list with tuple( ) function
>>> T = tuple(L)
>>> T
(100, 20, 30) # Now the tuple is changed
Predict the output of the following code:
a, b, c, *d = [1,2,3,4,5,6]
print(a)
print(b)
print(c)
print(d)

a, b, c, *d, e = [1,2,3,4,5,6]
print(a)
print(b) Execute the following functions on tuple.
print(c)  len()
print(d)  max()
print(e)  min()
 index()
 count()

You might also like