Indexing and slicing of arrays in python.
Indexing and slicing of arrays.
What is Indexing in python?
·
Indexing in Python means referring to
an element of an iterable by its position within the iterable.
·
Each character can be accessed using their index
number.
·
To access
characters in a string we have two ways:
·
Positive index number
·
Negative index number
In Python Positive indexing, we pass a positive index that we want to access in square brackets. The index number starts from 0 which denotes the first character of a string.
Example:
my_str = "Python Guides"
print(my_str[0])
output:
P
Negative indexing
example in Python
In negative indexing in Python, we pass the negative index
which we want to access in square brackets. Here, the index number starts from
index number -1 which denotes the last character of a string.
Example:
my_str =
"Python Guides"
print(my_str[-1])
s
Indexing in python string
String indexing in
python allows you to access individual characters
from the string directly by using the index. Here, “(str[3])” is
used to get “c”.
Example:
str = 'Welcome'
print(str[3])
output:
c
Slicing arrays
Slicing in python means taking elements from one given index to
another given index.
We pass slice instead of index like this: [
start:
end]
.
We can also define the step, like this: [
start:
end:
step]
.
If we don't pass start its considered 0
If we don't pass end its considered length of array in that
dimension
If we don't pass step its considered 1
Program:
import
numpy as np
output:
[2 3 4 5]
Note: The result includes the start index, but excludes the end index.
Slice
elements from index 4 to the end of the array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
output:
[5 6 7]
We can access
the array elements using the respective indices of those elements.
import array as arr
a = arr.array('i', [2, 4, 6, 8])
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[-1])
Arrays are mutable, and their elements can be changed in a
similar way like lists.
import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
# changing first element
numbers[0] = 0
print(numbers)
# Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers)
# Output: array('i', [0, 2, 4, 6, 8, 10])
insertion
opration
- By using +
operator: The resultant array is a combination of elements
from both the arrays.
- By using
append() function: It adds elements to the end of the array.
- By using
insert() function: It inserts the elements at the given index.
import array
s1 = array.array('i', [1, 2, 3])
s2 = array.array('i', [4, 5, 6])
print(s1)
print(s2)
s3 = s1 + s2
print(s3)
s1.append(4)
print(s1)
s1.insert(0, 10)
print(s1)