A contiguous part of an array is a subarray, and a contiguous part of a string is a substring. The order of elements remains the same relative to the original list or string for both of them.
Python makes obtaining a subarray or a substring very straightforward compared to most of the other programming languages.
In this article, we will learn how to obtain a subarray of an array using Python.
Obtain a Subarray of an Array Using Slicing in Python
In Python, we can get a subarray of an array using slicing. Extending indexing, which is an easy and convenient notation, can be used to slice an array or a string. It has the following syntax.
object[start : end : step]
Following is the explanation of each component.
object - A list or a string.
start - The starting index for slicing. The default value is
end - The ending index for slicing. Note that the value as this index is not a part of the end result. The default value is the length of the iterable object.
step - The number of increments between each index in the end result. By default, it is
Let us understand how to use this Python feature to get a subarray of an array with the help of some examples. Refer to the following code for the same.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = array[1 : 4] b = array[0 : 8] c = array[6 : ] d = array[ : 5] print(a) print(b) print(c) print(d)
[2, 3, 4] [1, 2, 3, 4, 5, 6, 7, 8] [7, 8, 9, 10] [1, 2, 3, 4, 5]
As we can see, the output contains all the indexes between the
start and the
end index (
start inclusive and
end exclusive). Moreover, when no value is set for the
start, the first index is considered by default, and when no value is set for the
end, the last value is considered by default.
We can extend this even further and apply slicing to each individual value of a list. We will create a list of strings and a list of lists and find a substring and a subarray for each string and list using list comprehension and slicing. List comprehension is an inline syntax for iterating over a list or lists and creating a new list.
Refer to the following code for the example discussed above.
a = [ "Hello", "World", "Computer", "Science", "GitHub", "StakeOverflow" ] b = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1.1, 2.2, 3.3, 4.4, 5.5], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], ["Q", "W", "E", "R", "T", "Y"], [True, False, None, None, False, True] ] x = [element[1 : 5] for element in a] y = [element[1 : 3] for element in b] print(x) print(y)
['ello', 'orld', 'ompu', 'cien', 'itHu', 'take'] [[2, 3], [2.2, 3.3], [0.2, 0.3], ['W', 'E'], [False, None]]
For each string in the list of strings, the above Python code concatenates characters present at indexes
4 into a new string and creates a new list of strings. And for the list of lists, it clubs together all the values at indexes
2 and creates a new list of lists. Furthermore, we store both the new lists in two new variables and print them.