Comprehension and filter in Arrays – Python

Arrays in Python are homogeneous, type-code specific, memory optimized and indexed based sequential data structure. Arrays in Python are very similar to Lists. Similar to Lists, Arrays also support comprehension, slicing and filter method() to create new arrays based on given conditions. Using comprehension, slicing and filter techniques we can manipulate and extract data from arrays in a concise and efficient manner.

Comprehension with Arrays

Comprehension is a technique that allows to manipulate and extract data from arrays in efficient manner. Comprehension provides shorter syntax to iterate (loop) through array elements and can use conditions to filter the elements. Syntax of comprehension with arrays:

array = array.array(type-code, expression for item in iterable if condition == True)

  • array.array() is the method to create an array object
  • expression is the expression which identifies the element to be added in the array.
  • for item in iterable is the for loop iterating over the iterable (like list, tuple, array, set) and item is the element from the iterable taken out using in operator.
  • if condition == True is the if statement with condition
# comprehension with array
print("comprehension with array")
import array as array

comprehension_array = array.array("h", [x for x in range(100) if x > 30 and x % 6 == 0])  # 2 conditions
print(comprehension_array)

print("\n---------------------------------------------------\n")

double_array = array.array("d", [13.43, 25.67, 32.54, 40.76, 80.89])
print(double_array)
comprehension_array = array.array("d", [x for x in double_array if x > 30.00])
print(comprehension_array)

In this program, we are creating two arrays using comprehension technique.

  • Scenario 1 – This shows how we can use range() method and 2 conditions to create an array using comprehension

Using array.array("h", [x for x in range(100) if x > 30 and x % 6 == 0]) => Using comprehension technique with for loop, we are iterating over the elements of range() method and for each element we are checking with 2 conditions. If element passed both conditions then it will be collected into list to return. Finally we are using array.array() method with type-code h (signed short) to create an array object. All elements should be of signed short. Final array is referenced by comprehension_array.

  • Scenario 2 – This show how we can iterate over another array elements and check for condition to create new array using comprehension

We have declared and initialized an array double_array with type-code d (double). Using comprehension technique with for loop, we are iterating over the elements of double_array and for each element we are checking with condition x > 30.00. If element passed this condition then it will be collected into a list to be returned. Finally we are using array.array() method with type-code d (double) to create an array object. Final array is referenced by comprehension_array.

Program Output

comprehension with array
array('h', [36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96])
---------------------------------------------------
array('d', [13.43, 25.67, 32.54, 40.76, 80.89])
array('d', [32.54, 40.76, 80.89])

From the program output => In scenario 1, we got an array of h (signed short) elements with each element satisfy both given conditions. In scenario 2, we got an array of d (double) elements with each element satisfy the given condition.

Slicing of Arrays

Slicing is a way to access a portion (or slice) of an array by specifying start, stop, and step arguments. Slicing can be used to extract elements from an array, reverse an array, or even modify a part of the array. Syntax for slicing using colon (:) operator.

sliced_array = array.object[start:end:step]

  • start (optional) – This is an optional parameter. This is an index position from where slicing to start. If start index is not given, then slicing will start from the first element (i.e. index 0) in the array. Start index position can be defined using positive indexing or on negative indexing.
  • end (optional) – This is an optional parameter with colon operator. Slice the element up to this index. If end index is not given, then search will happen till the last element in the array. Elements up-to [end – 1] index are taken in sliced array. End index position can be defined using positive indexing or on negative indexing. Default value of end, is total count of array elements.
  • step (optional) – This is also an optional parameter. step defines the jump in index position to get the next element in sliced array. By default, step is 1.
  • return value – It will return the sliced array as a result. Original array will remain same and a new sliced array will be returned. Even if we don’t have any element in sliced array this will not return any error.
# slicing of arrays
print("slicing of arrays")
import array as array   # import array module

double_array = array.array("d", [13.43, 25.67, 32.54, 40.76, 80.89, 60.0, 96.0])  # defined array

print(double_array[::])
print(double_array[0:])
print(double_array[:4])
print(double_array[-3:])
print(double_array[:-4])
print(double_array[0::-1])
print(double_array[:4:2])
print(double_array[-3::2])
print(double_array[:-4:-1])
print(double_array[0:5:2])
print(double_array[-6:-1:2])

In this program, we have defined an array double_array with type-code d (double). We are using colon (:) operator to slice a part of this array. We have shown multiple ways in which combination of start, end and step parameters can be used.

  1. double_array[::] => Using colon operator, but not passing any value to start, end or step parameters. Default values of these parameters will be used. start = 0, end = number of elements in array, step = 1.
  2. double_array[0:] => start = 0 (passed value), end = number of elements in array, step = 1
  3. double_array[:4] => end = 4 (passed value), start = 0, step = 1 (default values)
  4. double_array[-3:] => start = -3 (passed value), end = number of elements in array, step = 1
  5. double_array[:-4] => end = -4 (passed value), start = 0, step = 1 (default values)
  6. double_array[0::-1] => start = 0, end = -1 (passed values), end = number of elements in array
  7. double_array[:4:2] => end = 4, step = 2 (passed values), start = 0
  8. double_array[-3::2] => start = -3, step = 2 (passed values), end = number of elements in array
  9. double_array[:-4:-1] => end = -4, step = -1 (passed values), start = 0
  10. double_array[0:5:2] => start = 0, end = 5, step = 2 (passed values)
  11. double_array[-6:-1:2] => start = -6, end = -1, step = 2 (passed values)

Program Output

slicing of arrays
array('d', [13.43, 25.67, 32.54, 40.76, 80.89, 60.0, 96.0])
array('d', [13.43, 25.67, 32.54, 40.76, 80.89, 60.0, 96.0])
array('d', [13.43, 25.67, 32.54, 40.76])
array('d', [80.89, 60.0, 96.0])
array('d', [13.43, 25.67, 32.54])
array('d', [13.43])
array('d', [13.43, 32.54])
array('d', [80.89, 96.0])
array('d', [96.0, 60.0, 80.89])
array('d', [13.43, 32.54, 80.89])
array('d', [25.67, 40.76, 60.0])

filter() method with Arrays

Working of filter() method is similar to comprehension. filter() method creates an iterator that extracts elements from an iterable for which a specified function returns True. It’s especially useful for applying complex conditions.

filter(function, iterable)

  • function: A function that returns True or False for each element.
  • iterable: The iterable (e.g., list, array) on which filter will be applied
# filter with array
print("filter with array")
import array as array

filter_array = array.array("h", filter(lambda x: x > 30 and x % 6 == 0, array.array("h", range(100))))
print(filter_array)

print("\n---------------------------------------------------\n")

double_array = array.array("d", [13.43, 25.67, 32.54, 40.76, 80.89])
print(double_array)
filter_array = array.array("d", filter(lambda x: x > 30.00, double_array))
print(filter_array)

In this program, we are creating two arrays using filter() method.

  • Scenario 1 – This shows how we are creating an iterable (array) using elements from range() method and 2 conditions inside the filter() method

Using filter(lambda x: x > 30 and x % 6 == 0, array.array("h", range(100))) => Using filter() method with lambda function with 2 conditions. We are creating an iterable (array) using the element from range() method. Then, we are passing lambda function and iterable to filter() method. If element passed both conditions then it will be collected into collection to return. Finally we are using array.array() method with type-code h (signed short) to create an array object. All elements should be of signed short. Final array is referenced by filter_array.

  • Scenario 2 – This show how we can iterate over another array elements and check for condition to create new array using filter() method

We have declared and initialized an array double_array with type-code d (double). Using filter() method with lambda function and iterable (double_array), we are iterating over the elements of double_array and for each element we are checking with condition x > 30.00. If element passed this condition then it will be collected into a collection to be returned. Finally we are using array.array() method with type-code d (double) to create an array object. Final array is referenced by filter_array.

Program Output

filter with array
array('h', [36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96])
---------------------------------------------------
array('d', [13.43, 25.67, 32.54, 40.76, 80.89])
array('d', [32.54, 40.76, 80.89])

From the program output => In scenario 1, we got an array of h (signed short) elements with each element satisfy both given conditions. In scenario 2, we got an array of d (double) elements with each element satisfy the given condition.

Summary

In this article we learned about comprehension technique, slicing of array and filter() method. We explored following scenarios:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *