Continuation of Arrays methods

Today we discuss about arrays methods
Arrays can be accessed using negative indexes unlike C .C doesn't support negative indexes and it is also a advantage.
Consider list A =[1,2,3,4,5,6,7]
then last elements can be accessed using 'negative indexes'
A =[1,2,3,4,5,6,7]
print(A[-1]) # it prints last element in list
print(A[-2]) # it prints last but one element

Reverse:
A list in python can be reversed just by using reverse method , with out making any computation.
Let us just consider 'A' as list and we need to reverse,then following code does that
syntax :list_name.reverse( )
A=[ 1,2,3,4,'ho','a' ]
A.reverse()
print(A)
# output is ['a' ,'ho',4,3,2,1 ]
Reverse method returns a Null value and It modifies the list on which it is applied

PROBLEMS WHERE WE CAN USE REVERSE METHOD
problem statement:consider a list of numbers,your task is to print each element in reverse
explanation:
  • Take array with some data consider A =[ 1,4,5,6,2,3]
  • We need to print it in a reverse order then
  • we apply reverse method and print each element using a for loop or while loop
ALTERNATIVE:
We can just use slicing too,for accessing a list in reverse order.
just use A[ : : -1] .we can just access array elements in a reverse order.
A=[ 1,2,3,4]
print(A[: : -1])
#output is [4,3,2,1]
SLICING:
In C in order to retrieve a sub array we use a looping statement .
Unlike C here in python we can use slicing.This process reduces the effort.
Consider A =[ 1,2,3,4,5,6,7,8,9,0]
slicing is done using ' : ' and start index and end index
Syntax :
list_name[ start_index :end_index]
#in order to get only [1,2,3]
# we can use A[:3] where 2 is last index and if any start index is not shown then it is 0
# we can show as A[0:3]
print(A[0:3])
print(A[:3])
# output of two statements is [1,2,3]
We can even access in last order using negative indices. as said earlier in this section .
A =[1,2,3,4,5,6,7]
print(A[0:-1])
# it prints all elements except last element in list
print(A[:-2])
# prints elements except last two elements.