Python List Manipulation
Python List Manipulation
com
• LONG LIST
• L = [1,2,3,44,55,66,77,88,99,4,3,5,6,7,88,100,300
12,13,14,56,78]
• NESTED LIST
• L = [1,2,4,[100,200,300], 20]
• The above code will create List L with 5 elements because it will
count [100,200,300] as one element. Now L[3] is list of 3
elements
• To print if we write : L[1] it will display 2 and to print 200 we
have to write L[3][1] i.e. of 3rd index print 2nd value
• eval(„5+10‟) 15
• Y = eval(“2*5”)
• print(Y) 10
• Eval wil not only convert the values to int type but also interpret the
value as intended type i.e. if you enter float value it will convert it to
float or if it is list or tuple it will convert it.
• In above list items from mango to cherry are 0 to 4 and from cherry to
mango will be -1 to -5
0 1 2 3 4
Mango Apple Guaua Pomegranate cherry
-5 -4 -3 -2 -1
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
• If list element is large, it will store the reference in the list and
the values will be stored somewhere else.
• List elements are accessed just like string like str[2] means
character at 2nd index List1[2] means elements at 2nd index and
List1[1:3] means all items between index 1 to 2
• Although there are many similarities in String and List but there
are many difference between them also and the main
difference is Strings are immutable whereas Lists are mutable
• Just like String , We can use “for” loop to traverse the list.
val = [10,20,30,50,100]
for i in val:
print(i)
Program to print list elements along with their index (both +ve,-ve)
val = [10,20,30,50,100]
length = len(val)
for i in range(length):
print ("At Index ", i," and index ",i-length, 'is :', val[i])
• Python allows us to use all the relational operators on list like ==, >=,
<=,!=,>,<
• Python will compare individual elements of each list.
>>> L1=[1,3,5]
>>> L2=[1,3,5]
>>> L3=[1,5,3]
>>> L1==L2
True
>>> L1==L3
False
>>> L1<L2
False
>>> L1<L3
True
>>> L4=[1,3,6]
>>>L1<L4
True
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
• Joining List
• Jointing the 2 list is very easy, we can use (+) to join 2 or
more list
• Fruits=[“apple”,”mango”,”grapes”]
• Veg=[“spinach”,”carrot”,”potato”]
• Fveg = Fruits + Veg
• Fveg # [“apple”,”mango”,”grapes”,
“spinach”,”carrot”,”potato”]
• Remember: you can only add list with another list not
with int, float, complex, or string type.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
• String slicing
• Listname[start:End] # from start index to end-1 index
val = [10,20,30,40,1,2,3,100,200]
print(val[0:3])
print(val[3:8])
print(val[-4:-1])
val2 = val[2:-2]
print(val2)
print(val2[0:])
print(val[::-1])
val[5]=101
print(val[-8:-2])
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
val = [10,20,30,40,1,2,3,100,200]
print(val[3:50])
print(val[-20:4])
print(val[10:20])
val = [10,20,30,40,1,2,3,100,200]
print(val[2:9:3])
print(val[::3])
print(val[::-2])
val = [10,20,30,40,1,2,3,100,200,10,20,30,11,12,15,17,19,90,77,35]
slice1 = val[5:15:2]
slice2 = val[::4]
sum = 0
for x in slice1:
print(x,"==",end='')
sum+=x
print("Sum of slice1 elements are ",sum)
sum=0
for x in slice2:
print(x,"==",end='')
sum+=x
avg = sum / len(slice2)
print("Average of slice 2 =",avg)
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
items=["One","Two","Three","Four"]
items[0:2]=[1,2]
for i in items:
print(i,end=' ')
items[0:3]="Fantastic"
print()
for i in items:
print(i,end=' ')
>>> items=[1,2,3,4]
>>> items[3:]=“hello”
>>> items # [1,2,3,‟h‟,‟e‟,‟l‟,‟l‟,‟o‟], it will work because
string is also a sequence
But if you try to assign as:
items[3:] = 100 # Error
If we pass index which is more than highest range, then Python will
use next position after the highest index for e.g.
>>> items[100:200]=[111,222]
Python will append these values to the end of list
>>>items [1,2,3,‟h‟,‟e‟,‟l‟,‟l‟,‟o‟,111,222]
• So far we have worked with How the Lists are declared, How to
access individual elements of List, How to perform Slicing and so
on, Now we are going to deal with basic operation on list like :
Appending, Updating, Deleting items from List
Items = [10,20,30,40]
Items[3] = 100
Items [10,20,30,100]
• Deleting items from a List: to delete items from list we will use
del statement. To delete single item give index, and to delete
multiple items use slicing
• We can also use pop() to remove single elements, not list slices.
It not only deletes elements but also returns it. Both del and
pop() are same except pop() deletes and return the deleted
value.
>>>Items = [10,20,30,40,50,60,70]
>>>Items.pop() # if no index is passed last item will be deleted
70
>>>Items.pop(2)
30
We can also store the deleted values by pop() as:
N1 = items.pop()
N2 = items.pop(3)
• This function is used to get the index of first matched item from
the list. It returns index value of item to search.
• For example
>>> L1=[10,20,30,40,50,20]
>>> L1.index(20)
1 # item first matched at index 1
Note: if we pass any element which is not in the list then index
function will return an error: ValueError: n is not in the list
>>> L1.index(100) #Error
• 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()
• For example
>>> subject1=["physics","chemistry","cs"]
>>> subject2=["english","maths"]
>>> subject1.extend(subject2)
>>> subject1
['physics', 'chemistry', 'cs', 'english', 'maths']
Note: here subject1 will add the contents of subject2 in it without
effecting subject2
Like append(), extend() also does not return any value.
>>> subject3 = subject1.extend(subject2)
>>>subject3 # Empty
• append() allows to add only 1 items to a list, extend() can add multiple
items to a list.
>>> m1=[1,2,3,4]
>>> m2=[100,200]
>>> m1.append(5)
>>> m1
[1, 2, 3, 4, 5]
>>> m1.append(6,7)
>>> m1.append([6,7])
>>> m1
[1, 2, 3, 4, 5, [6, 7]]
>>> len(m1)
6
Now let us see extend() function
>>> m2
[100, 200]
>>> m2.extend(300)
>>> m2.extend([300,400])
>>> m2
[100, 200, 300, 400]
>>> len(m2)
4
>>> L1=[10,20,30,40,50]
>>> L1
[10, 20, 30, 40, 50]
>>> L1.insert(3,35)
>>> L1
[10, 20, 30, 35, 40, 50]
>>>
>>> L1=[10,20,30,40,50]
>>> L1
[10, 20, 30, 40, 50]
>>> L1.insert(0,5) #beginning
>>> L1
[5,10, 20, 30, 40, 50]
>>> L1.insert(len(L1),100) #last
>>> L1
[5,10, 20, 30, 40, 50,100]
>>> L1.insert(-10,2)
>>> L1
[2,5,10, 20, 30, 40, 50,100]
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
>>> L1=[10,20,30,40,50]
>>> L1.pop()
50
>>> val = L1.pop(2)
>>> val
30
>>> L1
[10, 20, 40]
>>>
This function removes all teh items from the list and the list
becomes empty list.
List.clear()
>>> L1=[10,20,30,40,50]
>>> L1.clear()
>>> L1
[]
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
This function returns the count of the item that you pased as an
argument. If the given item is not in the list, it returns zero.
>>> L1=[10,20,30,40,20,30,100]
>>> L1.count(20)
2
>>> L1.count(40)
1
>>> L1.count(11)
0
This function reverses the items in the list. This is done i place
i.e. It wil not create a new list . The syntax to use reverse() is:
>>> L1=[10,20,30,40,20,30,100]
>>> L1.reverse()
>>> L1
[100, 30, 20, 40, 30, 20, 10]
>>> L2=[11,22,33]
>>> L3=L2.reverse() #it will not return any value
>>> L3 # empty
[]
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com