List Manipulation
List Manipulation
List Manipulation
Declaring a list
To create a list, put the list elements in square brackets.
Indexing in a list begins from 0
Firstlist = ["France", "Belgium", "England"]
print(Firstlist)
Examples of list-
[ ] # list with no member, empty list
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ] # list of integers
list3 = ["a", "b", "c", "d"]
Empty list
• The empty list is [ ]. It is equivalent of 0 or ‘ ‘.
• You can also create an empty list as : L = list( )
• [ ] # list with no member, empty list
Nested list
A list can have an element in it, which itself is a list. Such a list is called nested list.
e.g. L1 = [3, 4 , [5,6], 7]
x=1
eval('x + 1') Output - 2
Traversing a List
Traversal means accessing and processing each element of it.
The for loop makes it easy to traverse or loop over the items in a list, as per following syntax:
for <item> in <list> : p
L=[‘p’,’y’,’t’,’h’,’o’,’n’] y
for a in L: t
print (a) h
o
n
Traversing a List using index value
L = [ ‘q’ , ‘w’ , ‘e’ , ‘r’ , ‘t’ , ‘y’ ] Value at index o is q
Length = len(L) Value at index 1 is w
for a in range(length) : Value at index 2 is e
print(“value at index”, a, “is”, L[a]) Value at index 3 is r
Output produced by above code: Value at index 4 is t
Value at index 5 is y
Comparing Lists
Comparison between lists can be done using standard comparison operators of Python, i.e. < , > ,
== , != etc.
For 2 lists to be equal, they must have the same number of elements and matching values.
In the case of int and float, they will be equal if they have the same matching values not
considering the decimal point.
Example-
L1=[1,2,3]
L2 =[1,2,3]
L3=[4,5,6]
L4=[‘a’,’b’,’c’]
L1==L2 True
L1==L3 False
L1==L4 False
List operations
Joining Lists
The concatenation operator + , when used with two lists, joins two lists.
The resultant list displays the elements of the 1st list followed by that of the 2nd.
Eg:-
A= [ 1,3,5]
B= [ 6,7,8]
A+B O / p [ 1,3,5,6,7,8]
Note- Both the operands must of list types. The following expressions can result into an error-
List + number , List + string
>>> a=[10,12,14,20,22,24,30,32,34]
>>> b=a[0:2]
>>> b O/p - [10, 12]
>>> b=a[0:-1]
>>> b O/p - [10, 12, 14, 20, 22, 24, 30, 32]
>>> b=a[3:-3]
>>> b O/p - [20, 22, 24]
>>> b=a[3:3]
>>> b [] --even if both limits are out of bounds, Python will not give any error and returns an
empty sequence.
a=[20,22,24]
>>> a[1]=28
>>> a O/p - [20, 28, 24]
b=a[2:30]
>>> b O/p - [24]
a=[10,12,14,20,22,24,30,32,34]
>>> b=a[-12:6]
>>> b O/p - [10, 12, 14, 20, 22, 24]
List also support slice steps. That is, if you want to extract, not consecutive but every other element of
the list, there is a way out – the slice steps. The slice steps are used as per following format:
seq = L[start : stop : step]
Example-
a=[10,12,14,20,22,24,30,32,34]
a[0:10:2] O/p - [10,14,22,30,34]
a[2:10:3] O/p - [14,24,34]
a[: : 3] O/p - [10,20,30]
Reversing a List
Abc = [5 ,6, 8, 11, 3]
Abc [ : : -1] Output- [3, 11, 8, 6, 5]
Built in Functions
Python offers various built in functions to perform different operations on lists
• APPEND List.append(elem)
• INSERT List.insert(index,elem)
• EXTEND List.extend(list 2)
• INDEX List.index(elem)
• REMOVE List.remove(elem)
• SORT List.sort( )
• REVERSE List.reverse( )
APPEND
It adds a single item to the end of the list. It doesn’t create a new list but modifies the original one.
Syntax is- List.append(item)
e.g : abc= ["apple", "banana", "cherry"]
abc.append(“plum")
PROGRAM
Create a list of items. Accept a new value to be added to the list. If the number is even then add it to
the list and display the sum of all the values. If the number is odd, then just display the message
“Enter an even number to find the sum”
a = [10,20,30,40]
b=int(input("Enter new value to be added : "))
a.append(b)
print("New list is : " , a)
if b%2==0:
sum = 0
for num in a:
sum=sum+num
print("Sum of the values = ",sum)
else:
print("Enter an even number to find the sum!!!!!!!!!!")
EXTEND
• The extend( ) method adds one list at the end of the other list.
• All the items of the list are added at the end of an already created list.
• It cannot add a single element; it requires a list to be added.
Syntax is- List.extend(list2)
Eg:- A=[5,3,2,6]
B = [10,11]
A.extend(B)
print (A) O/p- [5,3,2,6,10,11]
INSERT
• The insert( ) function inserts an item at a given index.
• It is used as per following syntax:
List.insert(index_number, value)
• Takes two arguments – index of the item to be inserted and the item itself.
T1 = [‘a’,’e’,’u’]
T1.insert(2,’’I’)
T1 O/p - [‘a’,’e’,’I’,’u’]
• If however, index is less than zero and not equal to any of the valid negative indexes of the list, the
object is prepended, i.e. added in the beginning of list.
• T1= [‘a’, ’e’, ’i’ , ‘o’ , ‘u’]
• T1.insert (-9, ‘k’)
• T1 O/p - [‘k’, ‘a’, ’e’, ’i’ , ‘o’ , ‘u’]
REVERSE
• This function reverses the order of the elements in a list.
• It does not create a new list but replaces a new value in place of the already existing items.
T1= [‘abc’ , ‘def’ , ‘ghi’ ]
T1.reverse ( )
T1 O/p- [‘ghi’ , ‘def’ , ‘abc’]
INDEX
• This function returns the index of first matched item from the list.
• Syntax - List.index (<item>)
• If the item is not in the list, an error is raised.
X = [12,14,15,17,18]
X.index(15) O/p- 2
X = ‘Python’
X.index(‘h’) O/p- 3
UPDATE
• Lists are mutable; we can assign new values to existing values.
• Assignment operator = is used to change an item or a range of items.
X = [12,14,15,17,18]
X[1] = 4 O/p- [12,4,15,17,18]
LEN
• Len() function returns the length of the list.
A = [6,’abc’,10,’new’]
print (len(A)) O/p- 4
SORT
• It sorts the items of the list in ascending or descending order.
• For strings, sorting is done on the basis of their ASCII values.
• To sort it in the decreasing order use, sort(reverse=True)
a=[10,4,8,20,100,65]
>>> a.sort()
>>> a O/p - [4, 8, 10, 20, 65, 100]
>>> a.sort(reverse=True)
>>> a O/p - [100, 65, 20, 10, 8, 4]
CLEAR
• It removes all the items from the list. It doesn’t take any parameters.
• It only empties the given list and does not return any value.
a=[10,4,8,20,100,65]
>>> a.clear()
>>> a O/ p - [ ]
COUNT
• This function counts how many times an element has occurred in a list.
• If the given item is not in the list, it returns zero.
• It is used as per following format: List.count(<item>)
a=[10,4,8,20,100,65]
>>> a.count(4) O/p - 4
DELETION OPERATION
• To delete or remove items from a list, there are many methods used-
Pop() or del () is used in cases the index is known.
Remove() is used if the element is known.
Del() with list slice is used to remove more than one element.
POP
• The pop() method removes the element from the specified index and returns the element which
was removed.
• An error is shown if the list is already empty.
List.pop(<index>) # index is optional; if skipped, last element is deleted.
X=[1,2,5,4,3,6,7,12,50]
>>> Y=X.pop(2)
>>> X O/p - [1, 2, 4, 3, 6, 7, 12, 50]
>>> Y 5
>>> X O/p - [1, 2, 4, 3, 6, 7, 12, 50]
>>> X.pop()
50
>>> X O/p - [1, 2, 4, 3, 6, 7, 12]
DEL
• It removes the specified element from the list but does not return the deleted value.
• An error is shown if an out of range index is specified with del() and pop().
>>> X [1, 2, 4, 3, 6, 7, 12]
>>> del X[5]
>>> X [1, 2, 4,3, 6, 12]
>>> X [1, 2, 4, 6, 7, 12]
>>> del X[-2]
>>> X [1, 2, 4, 6, 12]
REMOVE
• An element can be removed from the list using remove method.
• It is used when we know the element to be removed and not the index.
Eg: pqr= ["apple", "banana", "cherry"]
pqr.remove(“cherry”)
Program - # To display all the even and odd numbers from a list.
A=eval(input("Enter list: "))
print("Odd numbers- ")
for num in list1:
if num % 2 != 0:
print(num, end = " ")
print("\n")
print("Even numbers- ")
for num in list1:
if num % 2 == 0:
print(num, end = " ")
MAX - It returns the element with the maximum value from the list.
P=[10,20,30,40] max(P) O/p- 40
Q=[‘A’,’a’,’B’,’C’] Max(Q) O/p a Highest ASCII value
Q=[‘apple’,’bus’,’shell’]
Max(Q) O/p -shell Returns the string that starts with the character with highest ASCII value
MIN - It returns the element with the minimum value from the list.
P=[10,20,30,40] min(P) O/p - 10
If there are 2 or more strings that start with the same character, then the second character is
compared and so on.
a=[5,10,15,20,25]
k=1
i=a[1]+1
j=a[2]+1 [11 16 15]
m=a[k+1]
print(i,j,m)
str1=‘book’
print(list(str1) ['b', 'o', 'o', 'k']
L=['p','w','r','d','a']
L.remove('r') ['p', 'w', 'd', 'a']
print(L) a
print(L.pop()) ['p', 'd']
del L[1]
print(L)
L1=[500,600]
L2=[35,45]
L1.append(700)
L1.extend(L2) [500, 600, 700, 35, 45, 2]
L1.insert(25,2) [500, 600, 700, 35, 45, 2, 35, 45]
print(L1) [500, 600, 700, 35, 45, 2]
print(L1+L2) 3
print(L1) [35, 45, 35, 45]
print(L1.index(35))
print(L2*2)
#To display square if the element is an integer and to change case if it is a string
L=[10,"FUN",40,"FEW",50,"FULL"]
for i in range (len(L)):
if type(L[i])==int:
L[i]=L[i]**2
elif type(L[i]) ==str:
L[i]=(L[i]).swapcase()
print(L)
[100, 'fun', 1600, 'few', 2500, 'full']