DEV Community

Roshansahurk
Roshansahurk

Posted on

Array Methods

Array Methods

What are Arrays?

  • Arrays are the data structures which store the same data type of elements.

  • The data type includes integer, float and character values.

  • Arrays can store more than one item at the same time.

  • They are an ordered sequence of elements.

Difference between array and list

  • Arrays and lists are similar.

  • Arrays store only items that are of the same single data type but lists can store multiple data types.

  • Other properties are almost identical to each other.

Sample codes

  • array.array(datatype [array items])

    Initialise an array

    >>> import array
    
    >>> a = array.array('i', [1, 2, 3, 4, 5, 6]) 
    
  • a.typecode

    Return the type of the elements

    >>> a.typecode
    'i'
    
  • a.itemssize

    Returns length in bytes of one array item

    >>> a.itemsize
    4    
    
  • a.append(element)

    Adds a value at the end of an array

    >>> a.append(5)
    
    #TO KNOW THE OUTPUT 
    >>> a
    array('i', [1, 2, 3, 4, 5, 6, 5])
    
  • a.count(element)

    Number of occurrences of argument in the array

    >>> a.count(5)
    2
    
  • a.extend(iter)

    Append items from an iterable

    >>> a.extend([74,54,56])
    >>> a
    array('i', [1, 2, 3, 4, 5, 6, 5, 74, 55, 56])
    
  • a.insert(Index, element)

    Inserts an element in the index

    >>> a.insert(4, 99)
    >>> a
    array('i', [1, 2, 3, 4, 99, 5, 6, 5, 74, 55, 56])
    
  • a.pop()

    Returns the last element and pops out the last element from an array.
    On passing an argument in the pop method it removes the element from the index. It takes the argument as an index.

    >>> a.pop()
    56
    
  • a.reverse()

    Reverse an array

    >>> a.reverse()
    >>> a    
    array('i', [55, 74, 5, 6, 5, 99, 4, 3, 2, 1])
    
  • a.remove(element)

    Removes the first occurrence of the element

    >>> a.remove(5)
    >>> a
    array('i', [55, 74, 6, 5, 99, 4, 3, 2, 1])
    
    

Quick Overview of Array methods

Method Function
a.typecode Returns the type of element in the list
a.itemsize Returns the byte capacity of the single item in the array
a.count() Counts the number of occurrences in the array
a.append() Appends the value to an array
a.extend Appends an array to an array
a.insert() Inserts an element at the given index
a.pop() Pops out the last element from the array
a.reverse() Reverses the array
a.remove() Removes the element from the array

References

  • To search for the data type, click on the below link.

    Data type

Top comments (1)

Collapse
 
vulcanwm profile image
Medea

nice explanation!