Python Devlopment






List Slicing



A piece or subset of a list is known as slice. Slice operator is applied to a list with the use of square brace [ ]. Operator [m:n] will give a subset which consists of elements between m and n indices, including element at index m but excluding that at n, i.e. element from mth index to (n-1)th index.

Simillarly, Operator [m:n:s] will give a subset which consist of elements from mth index to (n-1)th index, where s is called the step value, i.e. after at m, that at m+s will included, then m+2s, m+3s,..etc.

1. List Slicing Operator [start:End] i.e. [m:n]

a=[10,20,30,40,50]
print(a[0:5])
print(a[2:5])

#Output
[10, 20, 30, 40, 50]
[30, 40, 50]

2. List Slicing with Step Size [m:n:s]

a=[10,20,30,40,50]
print(a[0:5:2])
print(a[0:5:3])

#Output
[10, 30, 50]
[10, 40]

 

3. List Slicing with Index [ : n] or [m:n]

a=[10,20,30,40,50]
print(a[:5])
print(a[2:])

#Output
[10, 20, 30, 40, 50]
[30, 40, 50]

 

4. String Slicing with Index [ : ] 

a=[10,20,30,40,50]
print(a[:])

#Output
[10, 20, 30, 40, 50]

 

5. String Slicing with Index [ : : -1]

Now if we give the value of step as -1 and no value for m and n then it will print the string in reverse order.

a=[10,20,30,40,50]
print(a[::-1])

#Output
[50, 40, 30, 20, 10]

Example 1:

Write a python program for addition of two matrices

a=[[4,8,18],
   [3,19,12],
   [15,6,9]]

b=[[8,32,23],
   [12,1,15],
   [5,12,3]]

c=[[0,0,0],
   [0,0,0],
   [0,0,0]]

for i in range(len(a)):
    for j in range(len(a[0])):
          c[i][j]=a[i][j]+b[i][j]

print("Addition of Two matrices is : \n")
for k in c:
    print(k)

#Output
Addition of Two matrices is :

[12, 40, 41]
[15, 20, 27]
[20, 18, 12]

 

Example 2:

Write a python program for Transpose of a given matrix.

a=[[4,8],
   [3,19],
   [15,6]]
tr=[[0,0,0],
    [0,0,0]]


for i in range(len(a)):
    for j in range(len(a[0])):
        tr[j][i]=a[i][j]

print("Given matrix is : ")
print(a)

print("Transpose of a given matrix is : ")
for k in tr:
    print(k)


#Output
Given matrix is : 
[[4, 8], [3, 19], [15, 6]]
Transpose of a given matrix is : 
[4, 3, 15]
[8, 19, 6]