Skip to content
thesarfo

Reference

Array Methods (Python & Java)

Reference for Python's array module methods and a Java array sort-and-search example.

views 0

The array objects support the following attributes and methods.

Array Methods (Python)

  1. a.typecode — the typecode character used to create the array.
  2. a.itemsize — size, in bytes, of items stored in the array.
  3. a.append(x) — appends item x to the end of the array.
  4. a.buffer_info() — returns the memory location and length of the buffer used to store the array.
  5. a.byteswap() — swaps the byte order of each item. Used for writing to a machine or file with a different byte order.
  6. a.count(x) — returns the number of occurrences of x in a.
  7. a.extend(b) — appends any iterable, b, to the end of array a.
  8. a.frombytes(s) — appends items from a string, s, as an array of machine values.
  9. a.fromfile(f, n) — reads n items, as machine values, from a file object f, and appends them to a. Raises an EOFError if there are fewer than n items available.
  10. a.fromlist(l) — appends items from list l.
  11. a.fromunicode(s) — extends a with unicode string s. Array a must be of type u or else ValueError is raised.
  12. a.index(x) — returns the first (smallest) index of item x.
  13. a.insert(i, x) — inserts item x before index i.
  14. a.pop([i]) — removes and returns the item at index i. Defaults to the last item (i = -1) if not specified.
  15. a.remove(x) — removes the first occurrence of item x.
  16. a.reverse() — reverses the order of items.
  17. a.tobytes() — converts the array to machine values and returns the bytes representation.
  18. a.tofile(f) — writes all items, as machine values, to file object f.
  19. a.tolist() — converts the array to a list.
  20. a.tounicode() — converts an array to a unicode string. The array type must be u or else a ValueError is raised.

Implementing an Array in Java

import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Declaring an array
int arr[] = {8, 5, 3, 10, 2, 1, 15, 20};
// Sorting the array
Arrays.sort(arr);
// Taking an element to search
int ele = 15;
// Using binarySearch() method to search "ele"
System.out.println(
ele + " presents at the index = " +
Arrays.binarySearch(arr, ele));
}
}